Question 1:
Write a Java class that represents a Student. The class should have fields to store the student's
name, age, and grades. Take the student's details as input from the user and calculate the average
grade with dynamic input from the user?
Input Format:
The user is prompted to enter the student's name.
The user is prompted to enter the student's age.
The user is prompted to enter the number of grades.
The user is prompted to enter each grade one by one, according to the number of grades entered.
Output Format:
The program will output the average grade for the student.
Title for Question 1: Average grades of students
Solution:
import java.util.Scanner;
public class Main {
private String name;
private int age;
private int[] grades;
public Main(String name, int age) {
this.name = name;
this.age = age;
}
public void setGrades(int[] grades) {
this.grades = grades;
}
public double calculateAverageGrade() {
if (grades == null || grades.length == 0) {
return 0.0;
}
int total = 0;
for (int grade : grades) {
total += grade;
}
return (double) total / grades.length;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//System.out.print("Enter the student's name: ");
String name = scanner.nextLine();
//System.out.print("Enter the student's age: ");
int age = scanner.nextInt();
scanner.nextLine();
//System.out.print("Enter the number of grades: ");
int numGrades = scanner.nextInt();
int[] grades = new int[numGrades];
for (int i = 0; i < numGrades; i++) {
System.out.print(+ (i + 1) + ": ");
grades[i] = scanner.nextInt();
}
Main student = new Main(name, age);
student.setGrades(grades);
double averageGrade = student.calculateAverageGrade();
System.out.println("Average grade for " + name + " is: " + averageGr
}
}
TestCases:
S.No Inputs Outputs
1 Sam 60 4 95 50 38 62 99 1: 2: 3: 4: Average grade for Sam is: 61.25
1: 2: 3: Average grade for Jane Smith is:
2 Jane Smith 25 3 95 88 77
86.66666666666667
3 Bob Johnson 22 0 Average grade for Bob Johnson is: 0.0
Alice Lee 18 7 92 89 95 85 1: 2: 3: 4: 5: 6: 7: Average grade for Alice Lee is:
4
88 91 86 89.42857142857143
5 Brown 30 4 75 80 78 82 1: 2: 3: 4: Average grade for Brown is: 78.75
6 Emma White 19 2 65 72 1: 2: Average grade for Emma White is: 68.5
Question 2:
The provided Java program demonstrates the use of a local inner class to calculate the factorial of
a user-input number. A local inner class, named Factorial, is defined within the main method. This
encapsulation allows the Factorial class to access and manipulate local variables of the enclosing
method. The program utilizes the Scanner class to dynamically obtain user input for the number
whose factorial is to be calculated. The Factorial class employs recursion to compute the factorial,
where the calculate method calls itself to repeatedly reduce the number and accumulate the
factorial result. The calculated factorial is then displayed to the user. This example showcases the
concept of local inner classes, their scope, and their ability to access outer method variables,
making them useful for encapsulating specialized logic within a specific context. The program also
highlights the role of user input handling and recursion in solving mathematical problems.
Expanding the program's functionality or reusing the local inner class outside the main method
raises intriguing questions about scope and design considerations.
Input Format: The program prompts the user to input a positive integer for which the factorial needs
to be calculated. The user should enter a single integer value.
Output Format: The program calculates the factorial of the input number using a local inner class
and displays the result.
Replace [User Input: Positive Integer] with the actual positive integer provided by the user and
[Input Number] with the same positive integer, and replace [Factorial Result] with the calculated
factorial value.
Title for Question 2: Factorial
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//System.out.print("Enter a number to calculate its factorial: ");
int number = scanner.nextInt();
scanner.close();
class Factorial {
int calculate(int num) {
if (num == 0 || num == 1) {
return 1;
} else {
return num * calculate(num - 1);
}
}
}
Factorial factorial = new Factorial();
int result = factorial.calculate(number);
System.out.println("Factorial of " + number + " is: " + result);
}
}
TestCases:
S.No Inputs Outputs
1 5 Factorial of 5 is: 120
2 0
3 7 Factorial of 7 is: 5040
4 4 Factorial of 4 is: 24
5 8 Factorial of 8 is: 40320
6 10 Factorial of 10 is: 3628800
Question 3:
Write a Java class that represents a Bank Account. The class should have methods to deposit and
withdraw money, and it should also keep track of the account balance. Take the initial balance and
transaction amounts as input from the user.
Input Format:
The user is prompted to enter the initial balance of the bank account.
The user is prompted to enter the amount to deposit into the bank account.
The user is prompted to enter the amount to withdraw from the bank account.
Output Format:
After each deposit, the program will output a message indicating whether the deposit was
successful or not, along with the new balance after the deposit.
After each withdrawal, the program will output a message indicating whether the withdrawal was
successful or not, along with the new balance after the withdrawal.
Title for Question 3: Deposit and withdraw
Solution:
import java.util.Scanner;
public class Main {
private double balance;
public Main(double initialBalance) {
balance = initialBalance;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. New balance: " + balance
} else {
System.out.println("Invalid amount. Deposit failed.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. New balance: " + bala
} else {
System.out.println("Insufficient funds or invalid amount. Withdr
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//System.out.print("Enter the initial balance: ");
double initialBalance = scanner.nextDouble();
Main account = new Main(initialBalance);
//System.out.print("Enter the amount to deposit: ");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
//System.out.print("Enter the amount to withdraw: ");
double withdrawAmount = scanner.nextDouble();
account.withdraw(withdrawAmount);
}
}
TestCases:
S.No Inputs Outputs
5000 700 Deposit successful. New balance: 5700.0 Withdrawal successful.
1
600 New balance: 5100.0
5000 1000 Deposit successful. New balance: 6000.0 Withdrawal successful.
2
6000 New balance: 0.0
Invalid amount. Deposit failed. Withdrawal successful. New balance:
3 200 -100 50
150.0
Invalid amount. Deposit failed. Insufficient funds or invalid amount.
4 000
Withdrawal failed.
1000 100 Deposit successful. New balance: 1100.0 Insufficient funds or invalid
5
2000 amount. Withdrawal failed.
Deposit successful. New balance: 1100.0 Withdrawal successful.
6 500 600 700
New balance: 400.0
Question 4:
Write a Java class that represents a ShoppingCart. The class should have a list of items and
methods to add items, remove items, and calculate the total cost of the items in the cart. Take item
details and quantities as input from the user with dynamic input from the user?
Input Format:
Select an option:
1. Add item
2. Remove item
3. Calculate total cost
4. Exit
The user can enter the corresponding option number to perform the desired action. Depending on
the option selected, the program will ask for additional input.
For option 1 (Add item), the user should provide the following input:
Item name (String)
Item price (double)
Item quantity (integer)
For option 2 (Remove item), if the cart is not empty, the user should provide the index of the item to
be removed (integer).
For option 3 (Calculate total cost), the program will display the total cost of all items in the cart.
For option 4 (Exit), the program will terminate.
Output Format:
The program will provide output based on the user's actions:
Title for Question 4: Shopping Cart
Solution:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Item {
private String name;
private double price;
private int quantity;
public Item(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
public double getTotalPrice() {
return price * quantity;
}
@Override
public String toString() {
return name + " - $" + price + " x " + quantity + " = $" + getTotalP
}
}
public class Main {
private List<Item> items;
public Main() {
items = new ArrayList<>();
}
public void addItem(Item item) {
items.add(item);
}
public void removeItem(Item item) {
items.remove(item);
}
public double calculateTotalCost() {
double total = 0;
for (Item item : items) {
total += item.getTotalPrice();
}
return total;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Main cart = new Main();
while (true) {
// System.out.println("\nSelect an option:");
// System.out.println("1. Add item");
//System.out.println("2. Remove item");
//System.out.println("3. Calculate total cost");
//System.out.println("4. Exit");
int option = scanner.nextInt();
scanner.nextLine();
if (option == 1) {
// System.out.print("Enter item name: ");
String name = scanner.nextLine();
//System.out.print("Enter item price: ");
double price = scanner.nextDouble();
//System.out.print("Enter item quantity: ");
int quantity = scanner.nextInt();
Item item = new Item(name, price, quantity);
cart.addItem(item);
System.out.println("Item added to cart: " + item);
} else if (option == 2) {
if (cart.items.isEmpty()) {
System.out.println("Cart is empty. Nothing to remove.");
} else {
System.out.print("Enter the index of the item to remove:
int index = scanner.nextInt();
if (index >= 0 && index < cart.items.size()) {
Item removedItem = cart.items.remove(index);
System.out.println("Item removed from cart: " + remo
} else {
System.out.println("Invalid index. Item removal fail
}
}
} else if (option == 3) {
if (cart.items.isEmpty()) {
System.out.println("Cart is empty.");
} else {
double totalCost = cart.calculateTotalCost();
System.out.println("Total cost of items in cart: $" + to
}
} else if (option == 4) {
break;
} else {
System.out.println("Invalid option. Please select a valid op
}
}
System.out.println("Thank you for using the ShoppingCart!");
}
}
TestCases:
S.No Inputs Outputs
Item added to cart: Toothpaste - $3.5 x 2 = $7.0 Exception in thread
"main" java.util.NoSuchElementException at
1 java.base/java.util.Scanner.throwFor(Scanner.java:937) at
1 Toothpaste java.base/java.util.Scanner.next(Scanner.java:1594) at
3.5 2 java.base/java.util.Scanner.nextInt(Scanner.java:2258) at
java.base/java.util.Scanner.nextInt(Scanner.java:2212) at
Main.main(Main.java:60)
Item added to cart: Soap - $1.5 x 3 = $4.5 Item added to cart:
Shampoo - $5.0 x 1 = $5.0 Exception in thread "main"
1 Soap 1.5 java.util.NoSuchElementException at
31 java.base/java.util.Scanner.throwFor(Scanner.java:937) at
2
Shampoo java.base/java.util.Scanner.next(Scanner.java:1594) at
5.0 1 java.base/java.util.Scanner.nextInt(Scanner.java:2258) at
java.base/java.util.Scanner.nextInt(Scanner.java:2212) at
Main.main(Main.java:60)
1 Chocolate
3 2.0 4 1 Milk
1.0 2 3
1 Brush 2.5
4
120
S.No Inputs Outputs
5 2
1 Cola 1.5 3
6
25
Question 5:
How does this Java program employ dynamic inputs to create instances of an inner class within an
outer class? Explain the purpose of parameterized constructors and their role in displaying values.
Input Format:
The program prompts the user to provide the following inputs:
Outer value (an integer)
Inner value 1 (an integer)
Inner value 2 (an integer)
Enter outer value: [User Input: Outer Value]
Enter inner value 1: [User Input: Inner Value 1]
Enter inner value 2: [User Input: Inner Value 2]
Output Format:
The program displays the following outputs:
Outer Value: [Outer Value]
Inner Value: [Inner Value 1]
Inner Value: [Inner Value 2]
Title for Question 5: Inner-Outer value
Solution:
import java.util.Scanner;
public class Main {
private int outerValue;
public Main(int value) {
outerValue = value;
}
public void displayOuter() {
System.out.println("Outer Value: " + outerValue);
}
// Inner class with parameterized constructor
public class Inner {
private int innerValue;
public Inner(int value) {
innerValue = value;
}
public void displayInner() {
System.out.println("Inner Value: " + innerValue);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//System.out.print("Enter outer value: ");
int outerValue = scanner.nextInt();
Main outerObj = new Main(outerValue);
outerObj.displayOuter();
//System.out.print("Enter inner value 1: ");
int innerValue1 = scanner.nextInt();
Main.Inner innerObj1 = outerObj.new Inner(innerValue1);
innerObj1.displayInner();
// System.out.print("Enter inner value 2: ");
int innerValue2 = scanner.nextInt();
Main.Inner innerObj2 = outerObj.new Inner(innerValue2);
innerObj2.displayInner();
scanner.close();
}
}
TestCases:
S.No Inputs Outputs
1 99 198 297 Outer Value: 99 Inner Value: 198 Inner Value: 297
2 123 Outer Value: 1 Inner Value: 2 Inner Value: 3
3 100 200 300 Outer Value: 100 Inner Value: 200 Inner Value: 300
4 7 14 21 Outer Value: 7 Inner Value: 14 Inner Value: 21
5 -8 -16 -24 Outer Value: -8 Inner Value: -16 Inner Value: -24
6 000 Outer Value: 0 Inner Value: 0 Inner Value: 0