Reputation: 37
This is for homework.
I am trying to create a program that takes the average of ten input numbers. When the user enters a character that is not a number, the NumberFormatException exception is caught. The program was finishing after the exception was caught, so I changed it to use recursion to call the method again after the exception is caught, but now it prints multiple averages, some of which are not correct.
How do I change the program so that it continues to ask for input after an exception has been caught instead of finishing? I do not want the program to finish after catching the exception.
import java.util.Scanner;
import java.util.Scanner;
public class PrintAverage {
int average;
public static void main(String args[]) {
System.out.println("You are going to enter ten numbers to find their average.");
getInput();
}
private static void getInput() {
String input;
int sum = 0;
int[] arrayOfIntegers = new int[10];
double average = 0;
Scanner scanner = new Scanner(System.in);
try {
for (int i = 0; i < arrayOfIntegers.length; i++) {
System.out.println("Enter the next number.");
input = scanner.nextLine();
arrayOfIntegers[i] = Integer.parseInt(input);
}
} catch (NumberFormatException exception) {
System.out.println("The last entry was not a valid number.");
getInput();
}
for (int k = 0; k < arrayOfIntegers.length; k++) {
sum = sum + arrayOfIntegers[k];
}
average = sum / arrayOfIntegers.length;
System.out.println("The average is " + average);
}
}
Upvotes: 1
Views: 54
Reputation: 6045
Localize the exception. Change this:
try {
for (int i = 0; i < arrayOfIntegers.length; i++) {
System.out.println("Enter the next number.");
input = scanner.nextLine();
arrayOfIntegers[i] = Integer.parseInt(input);
}
} catch (NumberFormatException exception) {
System.out.println("The last entry was not a valid number.");
getInput();
}
to this:
for (int i = 0; i < arrayOfIntegers.length; i++) {
System.out.println("Enter the next number.");
input = scanner.nextLine();
try {
arrayOfIntegers[i] = Integer.parseInt(input);
} catch (NumberFormatException exception) {
System.out.println("The last entry was not a valid number.");
i--; //so you don't lose one of the 10.
}
}
Upvotes: 1
Reputation: 5269
Your try/catch is not specific enough, so it catches the exception after asking all the numbers you want.
Upvotes: 3