I am trying to set up a program that saves users input into a file and then it outputs what the user entered as the average. I am using exception handling to detect if the user inputs letter. However, when the user inputs a letter it goes into an infinite loop. I am not able to figure out the issue. Please ignore the bad java. I just want it to function before I fix up the bad 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...");
}
}
You shouldn't declare your Scanner inside of your loop. As it stands now, you're initializing 10 different scanners and not closing any of them. It should be declared outside of your loop.
Your for nested inside of your do...while is also interesting. I don't think the inner for loop is necessary, because your do...while should already be taking care of the right bounds. If you do get rid of it, you would replace numArray[i] with numArray[numOf] (and start numOf at 0).