It can catch an exception that the app throw an exception in the block of try
.
In your block of try
, we just see average = totalScores / 3;
, it don't throw any exception. So it don't catch anything what was throwed.
You can use this function to throw an exception - IllegalArgumentException
.
public static int getInputScore(Scanner keyboard) {
int score = keyboard.nextInt();
if (score < 0 || score >= 100) {
throw new IllegalArgumentException();
}
return score;
}
And use it in main
code:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] scores = new int[3];
System.out.println("Score 1:");
try {
scores[0] = getInputScore(keyboard);
} catch (IllegalArgumentException e) {
System.out.println("Numbers were too low or high.");
return;
}
System.out.println("Score 2:");
try {
scores[1] = getInputScore(keyboard);
} catch (IllegalArgumentException e) {
System.out.println("Numbers were too low or high.");
return;
}
System.out.println("Score 3:");
try {
scores[2] = getInputScore(keyboard);
} catch (IllegalArgumentException e) {
System.out.println("Numbers were too low or high.");
return;
}
int totalScores = scores[0] + scores[1] + scores[2];
int average = totalScores / 3;
System.out.println("Average Score: " + average);
}