Gon49
Gon49

Reputation: 17

Java while loop continuously executing the code in catch block if error generated once

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?

Upvotes: 0

Views: 398

Answers (1)

Endercan Yılmaz
Endercan Yılmaz

Reputation: 26

You can change your catch block as:

catch (Exception e) {
      System.out.println("Please enter a valid input.");
      scanner.next();
}

Upvotes: 1

Related Questions