Java 2
Java 2
WORKSHEET 2
Aim: Design a calculator software that takes all sort of inputs robust enough to
perform all possible mathematical calculations and handles in case of some trouble
some situations.
1. Source Code:
import java.util.Scanner;
while (true) {
try {
System.out.println("Enter an expression (e.g., 2 + 3): ");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
System.out.println("Exiting calculator.");
break;
}
scanner.close();
}
switch (operator) {
case "+":
return operand1 + operand2;
case "-":
return operand1 - operand2;
case "*":
return operand1 * operand2;
case "/":
if (operand2 == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
return operand1 / operand2;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
default:
throw new IllegalArgumentException("Unsupported operator: " +
operator);
}
}
}
2. Screenshot of Outputs:
3. Learning Outcomes
i) Learnt about scanner class.
ii) Learnt about how to handle exception.
iii) Learnt about the arithmetic calculations.