-2

I am trying to write simple calculator and implement some exceptions. I want to catch exception InputMisMatchException if client will try to input letter instead number. I have already import java.util.Input... but this still doesnt work and it end program.

import java.util.InputMismatchException;
import java.util.Scanner;

public class Calculator {
    private static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        boolean menu = true;
        int choice;
        while (menu) {
            menuCalculator();
            System.out.println();
            System.out.println("Select operation: ");
            choice = sc.nextInt();
            sc.nextLine();
            switch (choice) {
                case 1:
                    try{
                    division();
                    } catch (InputMismatchException e){
                        System.err.println("Wrong input. Please enter valid value(s).");
                    }
                    break;
                case 5:
                    System.out.println("Shutting down calculator");
                    menu = false;
                    break;
            }
        }
    }

    public static void menuCalculator() {

        System.out.println("Press to go: \n 1. to divide \n 2. to multiplicate \n 3. to sum \n 4. to substract \n 5. to quit");
    }

    public static void division() {
        double firstNo;
        double secondNo;
        double result;

            System.out.println("Enter first number:");
            firstNo = sc.nextDouble();
            sc.nextLine();
            System.out.println("Enter second number:");
            secondNo = sc.nextDouble();
            sc.nextLine();
            result = firstNo / secondNo;
            if (secondNo == 0) {
                System.out.println("Cannot divide by 0");
            } else {
                System.out.println(firstNo + " / " + secondNo + " = " + result);
            }
    }
}
Matirix
  • 1
  • 2
  • read about try-catch. import a class doen not all what you have to do. – Jens Mar 24 '19 at 14:01
  • The exception is thrown by `nextInt`, but you don't have a `try`/`catch` around your call to `nextInt`, so it doesn't get caught. (Voting to close as typo/non-repro/not-useful-to-others-in-future.) – T.J. Crowder Mar 24 '19 at 14:02
  • 1
    What do you mean with "doesn't work"? – LppEdd Mar 24 '19 at 14:02

2 Answers2

1

The exception is thrown by nextInt, but you don't have a try/catch around your call to nextInt, so it doesn't get caught. Move your try/catch block so that the nextInt call is inside it. (You are handling the error from division's nextDouble, just not from nextInt.)

But: You might consider calling hasNextInt proactively, rather than dealing with the exception reactively. Both approaches have pros and cons.

Here's how you would use hasNextInt with a loop:

System.out.println("Select operation (1 - 5): ");
while (!sc.hasNextInt()) {
    sc.nextLine();
    System.out.println("Please entire a number [1 - 5]:");
}
choice = sc.nextInt();
sc.nextLine();
switch (choice) {
// ...

or to handle range checking as well, something like:

do {
    System.out.println("Select operation (1-5): ");
    choice = -1;
    if (!sc.hasNextInt()) {
        System.out.println("Please enter a number (1-5, inclusive)");
    } else {
        choice = sc.nextInt();
        if (choice < 1 || choice > 5) {
            System.out.println(choice + " isn't an option, please enter a number (1-5, inclusive");
        }
    }
    sc.nextLine();
} while (choice < 1 || choice > 5);
switch (choice) {
// ...
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • but if i set try/catch around sc.nextInt(); then i have to set try to whole code until switch case 5 end and then ok program catch this exception but I get infinity loop... – Matirix Mar 24 '19 at 14:16
  • @Matirix - It doesn't have to be around the whole code. But again, look at `hasNextInt` and a loop. – T.J. Crowder Mar 24 '19 at 14:21
  • it has to be around whole code because if I set try only around choice = sc.nextInt(); then i get error on switch statement that choice is not initialized. I dont get this hasNext with loop. :/ – Matirix Mar 24 '19 at 14:37
  • @Matirix - I've added an example to the question. – T.J. Crowder Mar 24 '19 at 14:43
  • ok thanks it looks nice but what If I am stubborn person and I want to use an try/catch exception?? :D I am trying to do loop that will allow me to back to the begining of the menu if I pick letter instead of number – Matirix Mar 24 '19 at 14:54
  • @Matirix - Just do the same thing with `try`/`catch` in the loop body. – T.J. Crowder Mar 24 '19 at 14:59
0

If you want to catch the Exception, then you have to surround the code that takes the Scanner input. You have misplaced your try-catch block, then it will work.

Pooya Panahandeh
  • 578
  • 7
  • 21