0

I wanted to print the multiplication table of a number. So I made a while(true) block to ontinously take inputs from the user. I also made a try and catch block, so that I could handle the exeptions.
Here is my code below :

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Getting the multiplication table of any number");
        while (true) {
            try {
                System.out.println();
                System.out.print("Enter a number: ");
                long number = scanner.nextLong();
                for (byte num = 1; num < 11; num++) {
                    System.out.println(number + "X" + num + " = " + (number * num));
                }
                System.out.println();
                System.out.println();
            } catch (Exception e) {
                System.out.println("Please enter a valid input.");
            }
        }
    }
}

When I run the programm, it run fine till I introduce just one error. Then it just gives the output:

Enter a number: Please enter a valid input.

Both the statements on the same line, And just continuosly prints the line without any delay or without letting me give it an input.
Why is this happening and how can I correct it?

Gon49
  • 17
  • 6
  • 4
    Does this answer your question? [try/catch with InputMismatchException creates infinite loop](https://stackoverflow.com/questions/12702076/try-catch-with-inputmismatchexception-creates-infinite-loop) – Federico klez Culloca Aug 10 '21 at 06:49

1 Answers1

1

You can change your catch block as:

catch (Exception e) {
      System.out.println("Please enter a valid input.");
      scanner.next();
}
  • Hello and welcome. That's the exact answer that is in the linked duplicate. We usually don't answer questions that are clearly duplicate of another one. – Federico klez Culloca Aug 10 '21 at 07:28
  • Thanks It did solved it. But my question is why was that error thing originating, and how did the statement "scanner.next()" corrected it. – Gon49 Aug 10 '21 at 07:32
  • @Gon49 it's in the duplicate I posted above. It's explained rather clearly. – Federico klez Culloca Aug 10 '21 at 07:33
  • @FedericoklezCulloca It could be that this is the exact same answer but actually the thing there wasn't working for me for some reason and I didn't really understood what they did there, – Gon49 Aug 10 '21 at 07:33
  • @Gon49 how could it not work? It's the EXACT same solution, i.e. call `next()` on the scanner. Plus, it explains how to not find yourself in that situation **and** why it happens. – Federico klez Culloca Aug 10 '21 at 07:38
  • @FedericoklezCulloca Actually it could be that I wasn't able to place the statemnts in the correct way as it was showing errors continuously. – Gon49 Aug 10 '21 at 07:40