Hello! So I'm working on a Java program that asks the user how many grades they would like to input, then asking them to enter those grades. From which it throws into an array, some math happens to get the average of those grades, the max grade given, etc. I am trying to do some exception handling so if the user tries to input an invalid value. Rather than throwing an 'InputMismatchException' it instead outputs, "Invalid Value/Amount" or the like. I've done something like this before, but can't quite remember how to do it. Any help is appreciated. I'll paste the code below:
What I've tried:
I've tried to use a boolean variable which should be in the code, to check if the given amount if an 'int' or not. If it is false, I was trying to have it in an if-statement to check and exit the program with the output before that. I've only tried that and moving it higher in my code thinking that perhaps I placed it in the wrong spot.
import java.text.DecimalFormat; import java.util.Scanner; public class testingCode { public static void main(String[] args) { //creating the scanner object Scanner input = new Scanner(System.in); //Creating our DecimalFormat DecimalFormat df = new DecimalFormat("0.00"); //Ask User for scores System.out.println("How many scores do you want to enter?"); //boolean variable to handle non-integer values boolean hasInt = input.hasNextInt(); int size = input.nextInt(); //if-statement handling amount of size is less than 0 or a non-integer if(size <= 0 || !hasInt) { System.out.println("Invalid Amount."); System.exit(0); }//end if-statement //Array int[] score = new int[size]; int max = -1; int sum = 0; System.out.println("Please enter in " + size + " scores between 0-50"); for(int index = 0; index < score.length; index++) { //take in the score and put it the array at the index score[index] = input.nextInt(); //compare the value of the variable at that index to max if(score[index] > max) max = score[index]; sum += score[index]; }//end for System.out.println("The max score is: " + max); double average = (double)sum/score.length; System.out.println("The average is: " + average); //standard deviation int total = 0; for(int index = 0; index < score.length; index++) { total += Math.pow(score[index] - average, 2); }//end for double standardDeviation = Math.sqrt(total * 1.0 / score.length); System.out.println("Standard Deviation: " + df.format(standardDeviation)); }//end main }//end class