Week 3: Java – Classes and Methods
Q1. Student Average Score
Objective: Create a class Student with a method to input student details and calculate the average of three exam scores.
import java.util.Scanner;
class Student {
static void Details() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.print("Enter score for exam 1: ");
float e1 = sc.nextFloat();
System.out.print("Enter score for exam 2: ");
float e2 = sc.nextFloat();
System.out.print("Enter score for exam 3: ");
float e3 = sc.nextFloat();
float finalMean = (e1 + e2 + e3) / 3;
System.out.println("Student: " + name);
System.out.println("Average score: " + finalMean);
sc.close();
}
}
public class q1 {
public static void main(String[] args) {
Student.Details();
}
}
Key Points:
staticmethod can be called without creating an object.Scanneris used for input.- Average calculation:
(e1 + e2 + e3) / 3. - Prints both student name and average.
Q2. Bank Account Operations
Objective: Simulate a simple bank account with deposit and withdrawal operations using a class.
import java.util.Scanner;
class BankAccount {
private String accountNumber;
private double balance;
public static void details() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your account number: ");
String accountNumber = sc.nextLine();
double balance = 0.0;
System.out.println("Account created with balance $0.00");
// Deposit
System.out.print("Enter deposit amount: ");
double deposit = sc.nextDouble();
balance += deposit;
System.out.println("Deposit Successful.");
System.out.println("Account: " + accountNumber + ", Balance: " + balance);
// First Withdrawal
System.out.print("Enter withdrawal amount: ");
double withdraw = sc.nextDouble();
if (withdraw <= balance) {
System.out.println("Withdrawal Successful.");
balance -= withdraw;
} else {
System.out.println("Insufficient balance.");
}
System.out.println("Account: " + accountNumber + ", Balance: " + balance);
// Second Withdrawal
System.out.print("Enter withdrawal amount: ");
withdraw = sc.nextDouble();
if (withdraw <= balance) {
System.out.println("Withdrawal Successful.");
balance -= withdraw;
} else {
System.out.println("Insufficient balance.");
}
System.out.println("Account: " + accountNumber + ", Balance: " + balance);
sc.close();
}
}
public class q2 {
public static void main(String[] args) {
BankAccount.details();
}
}
Key Points:
privatevariables (accountNumberandbalance) encapsulate data.- Deposit and withdrawal operations update the
balance. - Simple error checking: cannot withdraw more than balance.
- Uses
staticmethod to demonstrate class-level method access.
Week 3 Notes:
staticmethods allow calling without creating an object.Scannerinputs for different data types (String,int,float,double).if-elseis used for validation (like checking withdrawal amount).- Encapsulation: Use
privatefor sensitive data, can use methods for operations.