What's the proper way to structure this set of try catch blocks with respect to variable initializations?

Viewed 27

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?

1 Answers

Since the first initialization of d1 and d2 are within a try block, there is a possibility that those variables might not get initialized by the end of the first try block (in case of an exception). In such a case, you cannot use those variables to call calculate in the second try block, as those would still not be initialized.

just initialize as:

double d1 = 0d;
double d2 = 0d;
Related