public static void main(String[] args) {
int[] x = new int[3];
Scanner inputScan = new Scanner(System.in);
for(int i = 0; i < x.length; i++){
System.out.println("Please input the "+i+" integer:");
String inputInt = inputScan.nextLine();

try {
x[i] = Integer.parseInt(inputInt);
} catch (NumberFormatException e) {
System.out.println("您输入的日期格式有误,请重新输入");
i--;
}
}
System.out.println(Arrays.toString(x));
}

解决方案 »

  1.   

    要输入整数,使用 nextInt方法即可。
    是对API的错用。
      

  2.   


    那是不是应该换成nextInt,然后把这个放入try catch中?
      

  3.   


    如果这个小程序不加入异常处理(不是checked exception),那么当你输入错误的时候,整个程序就崩溃了....
      

  4.   


    如果是NumberFormatException,应该就可以执行到....
    当然在catch中放入i--这个代码的确让人有点不舒服
      

  5.   

    需要整数时,用 nextInt,这时你输入的不是整数的话捕获 java.util.InputMismatchException。
      

  6.   


    用 nextInt的话会产生问题
    for (int i = 0; i < x.length; i++) {
    System.out.println("Please input the " + i + " integer:");

    try {
    inputInt = inputScan.nextInt();
    x[i] = inputInt;
    } catch (InputMismatchException e) {
    e.printStackTrace();
    System.out.println("输入的不是数字,请重新输入:");
    i--;
    }

    }当输入非数字的时候,无限循环了....
      

  7.   

            Scanner scanner = new Scanner(System.in);
            int[] numbers = new int[3];
            int temp ;
            for (int i=0;i < 3 ;){
                try {
                    System.out.print("Please input a integer number:");
                    temp = scanner.nextInt();
                    numbers[i++] = temp;                
                }catch(InputMismatchException e){
                    scanner.next();
                }
            }
            System.out.println(Arrays.toString(numbers));Please input a integer number:a
    Please input a integer number:b
    Please input a integer number:3
    Please input a integer number:4
    Please input a integer number:1a
    Please input a integer number:34
    [3, 4, 34]
      

  8.   

    就lz需求而言,这段代码更好。但是lz的代码本身,算不上对异常的滥用。
      

  9.   


    为啥一定要在  catch中,放一个这个东西...是吸收缓冲区里面剩余的字符吗?
                    scanner.next();