gpt4 book ai didi

Java 比较值时没有这样的元素异常?

转载 作者:行者123 更新时间:2023-11-29 05:38:04 25 4
gpt4 key购买 nike

我正在创建一个提示用户输入 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

最佳答案

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

因此,要解决这个问题,请使用一个 Scanner,同时用于两个目的:

Scanner keyboard = new Scanner(System.in);
...
i1 = keyboard.nextInt();
i2 = keyboard.nextInt();
...
d1 = keyboard.nextDouble();
d2 = keyboard.nextDouble();
d3 = keyboard.nextDouble();

关于Java 比较值时没有这样的元素异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18725593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com