我正在尝试设置一个程序,将用户输入保存到文件中,然后输出用户输入的平均值。我正在使用异常处理来检测用户是否输入了字母。但是,当用户输入一个字母时,它会进入一个无限循环。我无法弄清楚这个问题。请忽略坏的java。我只是希望它在修复坏的 java 之前运行。
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Scanner;
public class W11dot1 {
public static void main(String[] args) throws IOException {
System.out.println("This program gets ten numbers from the user, then computes and displays the average.");
int numOf = 1;
double doMath = 0;
double[] numArray = new double[10];
do {
try{
for(int i = 0; i<10; i++){
Scanner input = new Scanner(System.in);
System.out.print("Enter Integer " + numOf + ": ");
double num = input.nextDouble();
numArray[i] = num;
numOf+=1;
}
}catch (InputMismatchException e){
System.out.println("Error: input must be an integer");
}
}while (numOf != 11);
File file = new File("Average.txt");
try {
PrintWriter output = new PrintWriter(file);
for(int y = 0; y<numArray.length; y++){
output.println(numArray[y]);
}
output.close();
} catch (IOException ex){
System.out.println("Error: with file");
}
Scanner input = new Scanner(file);
while (input.hasNext()){
double moreNums = input.nextDouble();
doMath += moreNums;
}
input.close();
double average = doMath/10;
System.out.printf("The average of the input values is %.2f", average);
System.out.println("\nGoodbye...");
}
}