I'm trying to calculate the average of N non-negative integers. I ask the user to input how many numbers they want to calculate the average of. Then ask them to input the numbers one by one. I'm also using a try and catch inside a do statement so I can re-prompt user again in case they input the wrong value.
How can I re-prompt user if any of the entered N numbers is not a number (int).? What I have re-prompts the user to restart again. I'd appreciate some directions!
Edit: I used the same do while loop to catch if input is non-numeric. What I get now is infinite number of prints that prints error and re prompt user to input. I have to stop program from running.
Edit: The problem was due to the scanner not getting cleared. Fixed by adding a second scanner inside nested do-while loop.
public class Average {
public static void main(String[] args) {
boolean flag = false;
do {
try {
System.out.println("Enter the number of integers you want to "
+ "calculate the average of: ");
Scanner input = new Scanner(System.in);
int value = input.nextInt();
int[] numbers = new int[value];
int sum = 0;
if( value == 0 ) {
throw new ArithmeticException();
}
boolean flag2 = false;
do{
try{
Scanner sc = new Scanner(System.in);
for( int i = 0; i < numbers.length; i++) {
System.out.println("Enter the " + (i+1) + " number: ");
numbers[i] = sc.nextInt();
sum += numbers[i];
flag2 = true;
}
} catch ( InputMismatchException e ) {
System.err.println("Cannot calculate average of non-numeric values.");
} catch ( NumberFormatException e) {
System.out.println("Cannot calculate average of non-numeric values.!!");
}
} while (!flag2);
double average = (double) sum / numbers.length;
System.out.println("The numbers you have entered are: " + Arrays.toString(numbers));
System.out.println("The sum of the numbers is: " + sum);
System.out.println("The number to divide by is: " + numbers.length);
System.out.println("The average of the numbers you have entered is: " + average);
flag = true;
} catch (InputMismatchException e) {
System.err.println("Input cannot be non-numeric values");
} catch (ArithmeticException e) {
System.err.println("Input can only be positive integers");
} catch (NegativeArraySizeException e) {
System.err.println("Input can only be positive integers");
}
} while (!flag);
}
}