用户错误后的反向扫描仪读取-java

用户错误后的反向扫描仪读取-java,java,Java,我读取的用户输入必须是int类型,当用户输入字母而不是int时会出现问题。我知道如何处理异常,但我想返回用户出错的扫描仪读取。我该怎么办? 我已经尝试使用无限循环,但它不起作用 try{ System.out.print("enter number: "); value = scanner.nextInt(); }catch(InputMismatchException e){ System.err.println("enter a number!"); } 循环是正确

我读取的用户输入必须是int类型,当用户输入字母而不是int时会出现问题。我知道如何处理异常,但我想返回用户出错的扫描仪读取。我该怎么办? 我已经尝试使用无限循环,但它不起作用

try{
    System.out.print("enter number: ");
    value = scanner.nextInt();
}catch(InputMismatchException e){
    System.err.println("enter a number!");
}

循环是正确的想法。您只需标记成功并继续:

boolean inputOK = false;
while (!inputOK) {
    try{
        System.out.print("enter number: ");

        numAb = tastiera.nextInt();

        // we only reach this line if an exception was NOT thrown
        inputOK = true;
    } catch(InputMismatchException e) {
        // If tastiera.nextInt() throws an exception, we need to clean the buffer
        tastiera.nextLine(); 
    }
}

循环是正确的想法。您只需标记成功并继续:

boolean inputOK = false;
while (!inputOK) {
    try{
        System.out.print("enter number: ");

        numAb = tastiera.nextInt();

        // we only reach this line if an exception was NOT thrown
        inputOK = true;
    } catch(InputMismatchException e) {
        // If tastiera.nextInt() throws an exception, we need to clean the buffer
        tastiera.nextLine(); 
    }
}

虽然其他答案给出了使用循环的正确想法,但您应该避免将异常作为基本逻辑的一部分。相反,您可以使用
Scanner
中的
hasNextInt
检查用户是否传递了整数

System.out.print("enter number: ");
while (!scanner.hasNextInt()) {
    scanner.nextLine();// consume incorrect values from entire line
    //or 
    //tastiera.next(); //consume only one invalid token
    System.out.print("enter number!: ");
}
// here we are sure that user passed integer
int value = scanner.nextInt();

虽然其他答案给出了使用循环的正确想法,但您应该避免将异常作为基本逻辑的一部分。相反,您可以使用
Scanner
中的
hasNextInt
检查用户是否传递了整数

System.out.print("enter number: ");
while (!scanner.hasNextInt()) {
    scanner.nextLine();// consume incorrect values from entire line
    //or 
    //tastiera.next(); //consume only one invalid token
    System.out.print("enter number!: ");
}
// here we are sure that user passed integer
int value = scanner.nextInt();

你能告诉我们你对循环的尝试吗?你能告诉我们你对循环的尝试吗?我想你应该添加
tastiera.nextLine()。因为当
Scanner
抛出异常时,它不会读取任何内容。所以,如果用户输入了无效的行,您的循环将永远不会结束。我认为您应该添加
tastiera.nextLine()。因为当
Scanner
抛出异常时,它不会读取任何内容。所以,如果用户输入无效的行,循环将永远不会结束