-2

I need to create a program that calculates the average of the test scores the user entered. This is actually the second time i've had an assignment asking to make this program. But this time the assignment wants me to throw an IllgalArgumentException whenever the user enters a testscore less than 0 or greater than 100. The problem is that no matter what test score even when the test score is between 0-100 the program crashes with an IllegalArgumentException. Not sure what i'm doing wrong any ideas here the expected output without the exception

Expected output

Enter number of test scores:5
Enter test score 1:70
Enter test score 2:65
Enter test score 3:94
Enter test score 4:55
Enter test score 5:90
74.8

and my code

public static void main(String[] args) throws IllegalArgumentException 
{
    Scanner input = new Scanner (System.in);
    int numTests = 0;
    int [] grade = new int [numTests];
    double average;
    double totalGrades = 0;

    System.out.print("Enter number of test scores:");
    numTests = input.nextInt();
    grade = new int[numTests];

    for (int index = 0; index < grade.length; index++)
    {
        System.out.print("Enter test score "  + (index + 1) + ":");
        grade[index] = input.nextInt();


            if(grade[index] < 0 || grade[index] > 100);
            {
                throw new IllegalArgumentException();

            }        
    }

    for (int i = 0; i < grade.length; i++)
    {
        totalGrades += grade[i];
    }

    average = totalGrades / grade.length;

    System.out.println(average);

}

private static class IllegalArgumentException extends Exception
{
    public IllegalArgumentException()
    {
        super("Test scores must have a value  less than  100 and greater than  0.");
    }

    public IllegalArgumentException(int value)
    {
        super("Invalid Test Score: " + value);
    }
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • 1
    Why do you declare a new class `IllegalArgumentException`? Why not just use `java.lang.IllegalArgumentException`, supplying the message you want as a parameter? – Andy Turner Apr 17 '17 at 21:53
  • @AndyTurner i originally didn't have the second but it was the displaying the error message as part of the loop so the error message came up 5 times and the program didnt crash – Christopher Collar Apr 17 '17 at 21:56

1 Answers1

5
if(grade[index] < 0 || grade[index] > 100);
{
  throw new IllegalArgumentException();
}

the ; on the end of the if line means the throw is executed unconditionally, because it's not in the conditional block.

Your code is (effectively) the same as:

if(grade[index] < 0 || grade[index] > 100) { /* do nothing */ }
throw new IllegalArgumentException();

Remove the ;.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243