문제

How do I make it so a "java.util.InputMismatchException" doesnt show?

For example:

import java.util.Scanner;

class Test {
  public static void main(String args[]){

    Scanner input = new Scanner(System.in);
    int number;

    System.out.print("Type a number: ");
    number = input.nextInt();
    System.out.println(number);

    input.close();
  }
}

It works fine when you type in a valid int, like "5", but when the user type an invalid int, like "5.1" or "a", it will give the error Exception in thread "main" java.util.InputMismatchException. Is there a way to bypass the error and display/do something else if the user types in a non-valid int?

Like so:

Type in a number: a
That is not a valid number. Try again
도움이 되었습니까?

해결책

First, you can catch the exception and do something you want.

A better way is use Scanner.hasNextInt() to test whether the line user input is a int.

System.out.println("Type a number");
while(!input.hasNextInt()) {
    input.nextLine();
    System.out.println("That is not a valid number. Try again");
}
number = input.nextInt();

다른 팁

number = input.nextInt();

The line above reads an integer. The exception means you're inputting something that is something else (e.g. String, double)

Note: if you want to read any number, replace that line with:

number = input.nextDouble();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top