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