【问题标题】:Prevent input error防止输入错误
【发布时间】:2013-11-13 05:53:16
【问题描述】:
import java.util.Scanner;

public class test {

    public static void main(String[] args) {
        System.out.print("Enter a number: ");
        Scanner keyboard = new Scanner(System.in);
        int x = keyboard.nextInt();

    }
}

我如何循环一段类似上面的代码,直到输入一个 int,而不是在输入非 int 时给出错误?

【问题讨论】:

  • 首先查看 Scanner 的 javadoc。然后尝试一下。

标签: java exception-handling int java.util.scanner


【解决方案1】:

Scanner 类内置了很多东西,因此您无需尝试捕获,除非您明确希望捕获错误。

public static int test(){
    int number = 0;
    Scanner input = new Scanner(System.in);
    boolean valid = false;
    do{
        System.out.print("Please enter an integer: ");
        if(input.hasNextInt()){ // This checks to see if the next input is a valid **int**
            number = input.nextInt();
            valid = true;
        }
        else{
            System.out.print("Not a valid integer!\n");
            input.next();
        }
    }while(valid == false);
    return number;

}

【讨论】:

    【解决方案2】:

    这会尝试运行扫描器,如果输入不是预期的输入,它将简单地重新启动。你可以给它添加一条消息,我的代码是为了简洁。

    import java.util.Scanner;
    
    public class test {
    
    public static void main(String[] args) {
        System.out.print("Enter a number: ");
        Scanner keyboard = new Scanner(System.in);
        try {
            int x = keyboard.nextInt();
        }
        catch (java.util.InputMismatchException e) {
            main(null);
        }
    }
    

    }

    【讨论】:

      猜你喜欢
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 2019-09-05
      • 1970-01-01
      相关资源
      最近更新 更多