Java在比较值时没有这样的元素异常?
我正在创建一个应用程序,提示用户输入3个数字,它将平均输入的数字。但当我到达那里时,它立刻引发了一个无趣的例外
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
# 1 楼答案
来自^{} 的文档
所以,当你做
keyboardInt.close();
时,它也关闭了System.in
。因此,当您试图调用.nextDouble()
时,扫描器没有任何东西可以解析成double
(因为底层流已关闭,因此没有读取任何内容),因此NoSuchElementException
要解决这个问题,可以使用一个
Scanner
来读取所有用户输入,并在完成后调用close()
# 2 楼答案
删除
keyboardInt.close()
语句。它关闭底层的InputStream,即System.in
。所以,当你创建keyboardDouble
时,它就不能再读了,因为System.in
是关闭的所以,要解决这个问题,使用一台扫描仪,你可以同时使用两种用途: