如何在java中处理用户输入类型?

时间:2015-06-14 09:32:57

标签: java

如果我的程序中允许的输入只是int类型,但是用户可以任意键入一个不允许的类型字符,例如doublechar等。我如何处理那?我确信有Throw exception类似的东西,但我不确定它是如何完成的。任何建议将不胜感激

//here is my code
System.out.print("Too " +additionalInfo+ "! Try again: ");
attemptCounter++;
int x= input.nextInt(); // here is where i want the usr to type in their input

1 个答案:

答案 0 :(得分:0)

使用循环在无效输入后再次提示用户输入,例如

    int userInput;
    while(true) {    
        try {
            System.out.println("Please enter a number: ");
            Scanner input = new Scanner(System.in);
            userInput = input.nextInt();
            break;
        }
        catch(InputMismatchException | NumberFormatException ex ) {
            System.out.println("Invalid Number, Please try again");
        }
    }
相关问题