1

我正在创建一个提示用户输入 3 个数字的应用程序,它将平均输入的这些数字。但是当我到达那里时,它会立即抛出 noSuchElementException。

    int i1,i2;
    int sum;
    double d1, d2, d3;//declares values input by the user
    double avg; //variable for calculating final result

    System.out.println("Hello out there. \n" //displays information to the user
            + "I will add two numbers for you. \n"
            + "Enter two whole numbers on a line:");

    Scanner keyboardInt = new Scanner(System.in); //Scans for keyboard input
    i1 = keyboardInt.nextInt();
    i2 = keyboardInt.nextInt();
    sum = (i1+i2);
    System.out.println("The sum of those 2 numbers is: \n" + sum + "\n" + 
    "Now enter 3 decimal numbers on a line:");
    keyboardInt.close();

    Scanner keyboardDouble = new Scanner(System.in); //Scans for keyboard input
    d1 = keyboardDouble.nextDouble();//-\ THIS LINE THROWS THE EXCEPTION. ID ASSUME THE OTHER WILL DO THE SAME
    d2 = keyboardDouble.nextDouble();//stores values entered by the user
    d3 = keyboardDouble.nextDouble();//-/
    avg = ((float) (d1+d2+d3)/3.0);//adds the sum of the values entered and calculates the average
    keyboardDouble.close();//closes scanner

    DecimalFormat df = new DecimalFormat("###,###,###.00");//formats the inputed number to 2 decimal places

    System.out.println("The average of those three numbers is:");//displays the average of the numbers
    System.out.println(df.format(avg));                         //entered by the user

这就是问题所在:

Scanner keyboardDouble = new Scanner(System.in); //Scans for keyboard input
d1 = keyboardDouble.nextDouble();//-\ THIS LINE THROWS THE EXCEPTION. ID ASSUME THE OTHER WILL DO THE SAME
d2 = keyboardDouble.nextDouble();//stores values entered by the user
d3 = keyboardDouble.nextDouble();//-/
avg = ((float) (d1+d2+d3)/3.0);//adds the sum of the values entered and calculates the average
keyboardDouble.close();//closes scanner     
4

2 回答 2

2

删除keyboardInt.close()声明。它关闭底层 InputStream,即System.in. 因此,当您创建时keyboardDouble,它无法再读取,因为System.in已关闭。

因此,要解决问题,请使用一个扫描仪,您可以同时使用:

Scanner keyboard = new Scanner(System.in);
...
i1 = keyboard.nextInt();
i2 = keyboard.nextInt();
...
d1 = keyboard.nextDouble();
d2 = keyboard.nextDouble();
d3 = keyboard.nextDouble();
于 2013-09-10T17:49:04.883 回答
1

从文档中Scanner#close

关闭此扫描仪。如果这个扫描器还没有关闭,那么如果它的底层可读也实现了 Closeable 接口,那么可读的 close 方法将被调用。如果此扫描仪已关闭,则调用此方法将无效。

所以,当你这样做时keyboardInt.close();,它也关闭了System.in。因此,当您尝试调用 时.nextDouble(),扫描仪没有任何东西可以解析为 a double(因为底层流已关闭,因此没有读取任何内容),因此NoSuchElementException.

解决这个问题的方法是使用一个Scanner来读取用户输入的所有内容,并close()在完成后调用。

于 2013-09-10T17:54:20.720 回答