0

I'm trying to error proof my program that basically works as a mini calculator. But I have no idea how to write a "Catch" statement that would detect when the user enters a case number that doesn't exist, in my case anything that is negative or > 4

        System.out.println("Hello user! Which operation would you like to use?");
        System.out.println("1) + \n2) - \n3) * \n4) /");


        Scanner operacijai = new Scanner(System.in);
        int operacija = operacijai.nextInt();


        int n=1;
        do {
        try {
            switch (operacija) {
            case 1:
                addingMethod();
                n=2;
                break;

            case 2:
                subtractingMethod();
                n=2;
                break;

            case 3:
                multiplyingMethod();
                n=2;
                break;

            case 4:
                dividingMethod();
                n=2;
                break;
                    }       
            }
            catch(Exception e) {
                System.out.print("Enter a correct number!");
            }

        } while(n==1);
        operacijai.close();

    } ```
Glamy
  • 1
  • 1
  • Use the "default" clause on your switch: https://www.w3schools.com/java/java_switch.asp – marcellorvalle Apr 05 '20 at 18:57
  • Wouldn't it be easier to get them to enter e.g. `+` instead of 1? (You can switch on a string) – Andy Turner Apr 05 '20 at 19:08
  • @marcellorvalle When I add the "default" clause it makes it go in a loop forever. – Glamy Apr 05 '20 at 19:08
  • @AndyTurner even if the switch would be + - / * I still want to somehow catch a faulty input so that the program would go back to the switch and ask for a correct input. – Glamy Apr 05 '20 at 19:15
  • @Glamy sure. Just mentioning that making users do the mental gymnastics of "if you want X please enter Y" is not very "error proof", if they could just enter "X" instead. – Andy Turner Apr 05 '20 at 19:24
  • @AndyTurner Ok, I totally agree with that, will keep that in mind. – Glamy Apr 05 '20 at 19:29

3 Answers3

2

Why do you want to throw an Exception unnecessarily? I suggest you just put a default case in your switch with the required error message. Also, move the input part inside the loop, so that it continues to take input.

I also suggest you use nextLine() instead of nextInt(). Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello user! Which operation would you like to use?");
        System.out.println("1) + \n2) - \n3) * \n4) /");
        Scanner operacijai = new Scanner(System.in);
        int operacija = 0, n = 1;
        boolean valid;
        do {
            do {
                valid = true;
                try {
                    operacija = Integer.parseInt(operacijai.nextLine());
                } catch (NumberFormatException e) {
                    System.out.println("Enter an integer only.");
                    valid = false;
                }
            } while (!valid);
            switch (operacija) {
            case 1:
                System.out.println("addingMethod()");
                n = 2;
                break;

            case 2:
                System.out.println("subtractingMethod()");
                n = 2;
                break;

            case 3:
                System.out.println("multiplyingMethod()");
                n = 2;
                break;

            case 4:
                System.out.println("dividingMethod()");
                n = 2;
                break;
            default:
                System.out.println("Invalid input");
            }
        } while (n == 1);
    }
}

A sample run:

Hello user! Which operation would you like to use?
1) + 
2) - 
3) * 
4) /
5
Invalid input

Another sample run:

Hello user! Which operation would you like to use?
1) + 
2) - 
3) * 
4) /
a
Enter an integer only.
5
Invalid input
2
subtractingMethod()
Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72
  • 1
    But the most significant change in your answer is something you've not mentioned explicitly: moving the `operacija =` inside the loop. – Andy Turner Apr 05 '20 at 19:20
  • Thanks, @AndyTurner for the feedback. I forgot to mention that in the explanation. I've done it now. – Arvind Kumar Avinash Apr 05 '20 at 19:23
  • @AndyTurner Yes, I moved the Scanner variable inside the loop, makes sense when I think about it a little bit, BUT now when I enter a faulty input the first time it says nothing but when I enter it again it works as intended.(As in enter 5 once, nothing happens, enter 5 again, works.) – Glamy Apr 05 '20 at 19:24
  • @Glamy - This problem is related to https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo . Let me update my answer as well with this info. – Arvind Kumar Avinash Apr 05 '20 at 19:26
  • @ArvindKumarAvinash Your answer was helpful, but as i commented before, it only prints out the default statement once I have entered the incorrect answer twice which is wierd... – Glamy Apr 05 '20 at 19:33
  • @Glamy - Don't worry, we will help you fix it. Can you edit your question and post the complete program? It seems there is some dangling newline character which is causing the issue. – Arvind Kumar Avinash Apr 05 '20 at 19:36
  • @Glamy - I've just updated my answer with a complete program to simulate the input and output. I can't find any problem with the logic. I've also posted some sample runs so that you can compare your results. Feel free to comment in case of any issue/doubt. – Arvind Kumar Avinash Apr 05 '20 at 19:49
  • @Glamy - I hope the solution worked for you. Do not forget to accept the answer so that future visitors can also use the solution confidently. Check https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work to learn how to do it. Feel free to comment in case of any doubt/issue. – Arvind Kumar Avinash May 18 '20 at 17:31
0

You can also handle the use case in default It is totally upto your use-case how you are handling the exception, you can also create your custom exception and throw from default something like:

    System.out.println("Hello user! Which operation would you like to use?");
    System.out.println("1) + \n2) - \n3) * \n4) /");


    Scanner operacijai = new Scanner(System.in);
    int operacija = operacijai.nextInt();


    int n=1;
    do {
    try {
        switch (operacija) {
        case 1:
            addingMethod();
            n=2;
            break;

        case 2:
            subtractingMethod();
            n=2;
            break;

        case 3:
            multiplyingMethod();
            n=2;
            break;

        case 4:
            dividingMethod();
            n=2;
            break;
        default:
            System.out.print("Enter a correct number!")
            throw new CustomException();
        }       
      }
      catch(CustomException e) {
          System.out.print("Enter a correct number!");
      }

    } while(n==1);
    operacijai.close();

}
0

With the help of my dad this seems like an optimal way of doing this, except for the + - * / instead of 1, 2, 3, 4

        System.out.println("Hello user! Which operation would you like to use?");
        System.out.println("1) + \n2) - \n3) * \n4) /");


        Scanner operacijai = new Scanner(System.in);
        int operacija;

        do {
            operacija = operacijai.nextInt();
            switch (operacija) {
            case 1:
                addingMethod();
                break;

            case 2:
                subtractingMethod();
                break;

            case 3:
                multiplyingMethod();
                break;

            case 4:
                dividingMethod();
                break;

            default:
                    System.out.print("Enter a correct number!");

                    }       

        } while(operacija < 1 || operacija > 4);
        operacijai.close();

    }
Glamy
  • 1
  • 1