如何通过验证用户的输入只是数字来向元素添加元素?

时间:2016-03-22 05:12:32

标签: java arrays

我试图在我的阵列中添加3个元素,但我想确保用户的输入只是数字。到目前为止,我有我的for循环,允许用户输入3个数字,如果用户输入的输入不是一个数字,我减去1,所以我仍然确保我只得到3个数字。运行我的代码后,我得到一个异常错误(线程中的异常" main" java.util.InputMismatchException)。请有人告诉我,我做错了什么。先感谢您!

     int[] arr = new int[3];

     for (int i = 0 ; i < arr.length ; i++) {
            try
            {
               System.out.println("Please enter a number: ");
               arr[i] = scan.nextInt();
            }
            catch(Exception ex)
            {
                i--;
               System.out.println("Please enter a valid number");
               arr[i] = scan.nextInt();
            }
        }

2 个答案:

答案 0 :(得分:2)

当下一个标记不是int时,调用scan.nextInt()将不会使用该标记。相反,您应该通过调用int(在scan.next()块中)来使用非catch。像,

for (int i = 0; i < arr.length; i++) {
    try {
        System.out.printf("Please enter a number for arr[%d]:%n", i);
        arr[i] = scan.nextInt();
    } catch (Exception ex) {
        i--;
        System.out.printf("%s is not a number.%n", scan.next());
    }
}

答案 1 :(得分:2)

使用hasNextInt()检查下一个令牌是否为int。 请参阅以下代码:

for (int i = 0; i < arr.length; i++) {
    try {
        System.out.printf("Please enter a number: ");
        if(scan.hasNextInt()){
            arr[i] = scan.nextInt();
        }else{
           i--;
           System.out.println(scan.next() + " is not a number.", );
         }
    } catch (Exception ex) {
    }
}