-2

T student Im wondering if the user input a Character not an integer.How can i Show the word INVALID to him and let him Type again.

EXAMPLE:

input a two number

a

INVALID try Again:1

2

Sum of two number=3

public static void main(String[] args) {
    int x = 0, y, z;

    System.out.println("Enter two integers to calculate their sum");
    Scanner in = new Scanner(System.in);

    try {
        x = in.nextInt();
    } catch (InputMismatchException e ) {
        System.out.print("INVALID");
    }

    y = in.nextInt();
    z = x + y;

    System.out.println("Sum of the integers = " + z);
}
deHaar
  • 11,298
  • 10
  • 32
  • 38
Hero Man
  • 1
  • 1

1 Answers1

1

You can do for example:

            while(true) {
                try {
                    x = in.nextInt();
                    break;
                  } catch (InputMismatchException e ) {
                    System.out.print("INVALID try again:");
                    in.next(); //To wait for next value otherwise infinite loop
                  }
            }

Basically you need to add the input into a loop and keep looping until you get valid input. You can write it in different ways but that should be the idea.

The in.next() in the catch is required because nextInt() doesn't consume the new line character of the first input and this way we skip to that.

If I were you I would use in.nextLine() for each line of parameters and the manipulate the String that I get to check for valid input instead of waiting for exception.

Veselin Davidov
  • 6,886
  • 1
  • 13
  • 21