I'm practicing java by trying my hand at a simple calculator challenge from an online course. The purpose is to take numeric inputs plus the desired operation (+, -, %, *), while also handling non numeric inputs and unlisted operators. Below is my attempt:
public static void main(String[] args) {
double d1;
double d2;
Scanner sc = new Scanner(System.in);
try {
d1 = getInput(sc);
d2 = getInput(sc);
} catch (InputMismatchException e) {
System.out.println("Non numeric value entered.");
System.exit(0);
}
try {
System.out.println(calculate(sc, d1, d2));
} catch(OperationNotSupportedException e){
System.out.println(e.getMessage());
}
}
private static double calculate(Scanner scanner, double d1, double d2) throws OperationNotSupportedException {
System.out.print("Enter the desired operation: ");
String op = scanner.next();
System.out.println(op);
switch (op) {
case "-":
return d1 - d2;
case "+":
return d1 + d2;
case "*":
return d1 * d2;
case "/":
return d1 / d2;
default:
throw new OperationNotSupportedException("The operation not one of (+ - % *)");
}
}
private static double getInput(Scanner sc) {
System.out.printf("Enter a numeric value: ");
return sc.nextDouble();
}
So the issue is that compiler sees a problem in the second try-catch block. Namely d1 and d2 may not have been initialized. I can see why that would be true in the case that an error is thrown in the first try-catch. I figured that putting System.exit() might satisfy the compiler, but it didn't.
How could I restructure my code to achieve the desired results?