0

I refreshing my Java skills, say we've got this code

public class HelloWorld extends Exception {
    public static int tenMultiplication(int x) {
        for (int i = 2; i < 11; i++) {
            System.out.println(x * i);
        }
        return x;
    }

    public static String scanExpression() {
        Scanner scan = new Scanner(System.in);
        String exp = "";

        do {
            System.out.println("Please enter a number:");

            try {
                exp = scan.nextLine();
                int result = Integer.parseInt(exp);
                tenMultiplication(result);
            } catch (NumberFormatException e) {
                System.out.println("Please enter a number: ");
            }
        } while (exp.matches("-?\\d+") || exp == "exit");

        return exp;
    }

    public static void main(String args[]) throws Exception {
       scanExpression();
    }
}

Program logic: Program asks for an input, and draws a row of multiplication table till 10; any time you can exit by typing "exit", everything else is an error.

Every time I write an incorrect number, it will simply catch an error and exit the program. What is the best way with going about iteratively catching errors if you consecutively type non-Ints and not "exit" to exit the program? I tried putting

exp = scan.nextLine();
int result = Integer.parseInt(exp);
tenMultiplication(result);

But when trying to write an error here, it throws the error again, which defeats the point of my try { } catch blocks.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Russel B
  • 33
  • 7
  • 2
    `exp == "exit"` - See: [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Jacob G. Jul 06 '18 at 14:00
  • Honestly, there are many good books and tutorials out there teaching such things. And unrelated: there is absolutely no point in calling a class HelloWorld to then extend Exception. Your class has to deal with exceptions - that doesn't mean at all that your example class should **be** an Exception! – GhostCat Jul 06 '18 at 14:19

3 Answers3

2

You need to re-read the input in case NumberFormatException is caught, you can do it in a recursive way by by calling your function again

public static void scanExpression(Scanner scan) {

        System.out.println("Please enter a number:");

        try {
            String exp = scan.nextLine();
            if(exp.equals("exit"))
                System.exit(0);
            int result = Integer.parseInt(exp);
            tenMultiplication(result);
        } catch (NumberFormatException e) {scanExpression(scan);}

}

public static void main(String args[]) throws Exception {

    Scanner scan = new Scanner(System.in);
    scanExpression(scan);
}
Elgayed
  • 1,129
  • 9
  • 16
0

After the catch block executes the program continues and goes to check the condition in the while statement. The while statement returns false for that condition so your program terminates. Plus you need to compare exp like this: exp.equals("exit").

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Mike
  • 706
  • 7
  • 16
0

Here are some changes I made to your loop.

  do {
      System.out.println("Please enter a number:");

      try {
          exp = scan.nextLine();
          int result = Integer.parseInt(exp);
          tenMultiplication(result);
      } catch (NumberFormatException e) {

      }
  } while (!exp.equals( "exit") );

I made your catch block empty. The reasoning is that if it does catch invalid input from the user, "Please enter a number:" would print twice.

Also, I modified your while loop condition. Previously you had exp == "exit". This doesn't work the way you expect it to work. When comparing String values, always use `String1.equals(String2) to see if String1 and String2 are equal.

user3170251
  • 310
  • 1
  • 13