7

I'm trying to work on a Java assignment. This is what it asks:

Write a class named TestScores. The class constructor should accept an array of the test scores as its argument. The class should have a method that returns the average of the test scores. If an test score in the array is negative or greater than 100, the class should throw an IllegalArgumentException. Demonstrate. I need a file named TestScores and TestScoresDemo.

This is what I have so far. I know some of it is wrong and I need help fixing it:

class TestScores {
    public static void checkscore(int s) {
        if (s<0) throw new IllegalArgumentException("Error: score is negative.");
        else if (s>100) throw new IllegalArgumentException("Error Score is higher then 100");
        else if (s>89)throw new IllegalArgumentException("Your grade is an A");
        else if (s>79 && s<90)throw new IllegalArgumentException("Your grade is an B");
        else if (s>69 && s<80)throw new IllegalArgumentException("Your grade is an C");
        else if (s>59 && s<70)throw new IllegalArgumentException("Your grade is an D");
        else if (s<60)throw new IllegalArgumentException("Your grade is an F");

        {
            int sum = 0; //all elements together
            for (int i = 0; i < a.length; i++)
                sum += a[i];
        }
        return sum / a.length;
    }
}

class TestScoresDemo {
    public static void main(String[] args) {
        int score = 0;
        Scanner scanner = new Scanner(System.in);
        System.out.print(" Enter a Grade number: ");
        String input = scanner.nextLine();
        score = Integer.parseInt(input);
        TestScores.checkscore(score);
        System.out.print("Test score average is" + sum);
    }
}

I know the assignment calls for a try statement because in my book that's what I see with the IllegalArgumentException. Can anyone help me? I'm using Eclipse as an IDE.

APerson
  • 8,140
  • 8
  • 35
  • 49
Alexandria
  • 87
  • 1
  • 1
  • 3
  • 2
    Why do you think this is wrong? Do you get an error message you shouldn't? We can't help if we don't know what part needs fixing. – Louis Wasserman Apr 27 '12 at 03:00
  • Thank you. Let me double check and get back to you. Maybe its just a simple type error – Alexandria Apr 27 '12 at 03:04
  • 8
    you should only be throwing an `IllegalArgumentException` in the cases where the argument is not valid in your case below 0 or above 100. – twain249 Apr 27 '12 at 03:05

3 Answers3

4

Your TestScores class should have two members: a constructor that accepts an array of scores and a method that returns the average of the scores. The assignment isn't totally clear as to which of these should throw an IllegalArgumentException if a test score is out of range, but I'd make it the constructor (since that's what has the argument).

public class TestScores {
    public TestScores(int[] scores) throws IllegalArgumentException {
        // test the scores for validity and throw an exception if appropriate
        // otherwise stash the scores in a field for later use
    }

    public float getAverageScore() {
        // compute the average score and return it
    }
}

You're on the right track with your TestScoresDemo class. It will first need to collect a set of scores into an array. Then it should construct a TestScores object. This is what needs to be inside a try/catch block because it can throw an exception. Then you just need to call getAverageScore() and do something with the result.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • Thank you everyone. I'll try to revise it. For some reason im really lost on this assignment. – Alexandria Apr 27 '12 at 03:22
  • @Alexandria - You're trying to do too much in your `checkscore` method. It should just check the score and throw an `IllegalArgumentException` if appropriate; it should not do anything else. Write other methods (and a constructor) to do other parts of the problem. That should help you get back on track. – Ted Hopp Apr 27 '12 at 03:34
0

An exception is something used to define something that didn't go right on the normal flow of an application. You have to throw the IllegalArgumentException when the method checkScore is called and it finds any argument outside the range (between 0 and 100).

Your class should have this structure:

public class TestScore {

    private int scores[]; //With setters and getters.

    public TestScore(int scores[]) {
        //Here, you set the scores array to the one on this class.
    }

    public int getAverage() {
        //You do the average here, and since you need to iterate over the 
        //array to sum each value, you can check the value and if it's not
        //ok you throw the IllegalArgumentException. No throws keyword
        //required since this kind of exception (like NullPointerException
        //and many others) are unchecked exceptions, meaning they can be 
        //thrown by a method and it does not need to specify them.
    }

}

The test class should create a TestScore object with an int array as a parameter of its constructor. Then you make a testAverageScore method that has the try-catch statement on it, since it's required to call the getAverage method.

Hope that helps. Good luck!.

EDIT: IllegalArgumentException is an unchecked exception.

Fritz
  • 9,987
  • 4
  • 30
  • 49
  • No need for a setter for `scores`; it's passed in the constructor. (It could even be `final`.) – Ted Hopp Apr 27 '12 at 03:32
  • It was just to start encouraging the use of standards. What if on the future he wants to set a new array to the same object? – Fritz Apr 27 '12 at 03:33
  • From the [Java Tutorial](http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html): "An object is considered _immutable_ if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code." – Ted Hopp Apr 27 '12 at 03:37
  • The problem doesn't specify any constraints for the TestScore object, so both options are valid. – Fritz Apr 27 '12 at 03:43
-1
public class TestScores {
private final int[] scores;

public TestScores(int[] scores) {
    this.scores = scores;
}

public int getAverage() {
    int sum = 0;

    if(scores.length == 0) {
        return 0;
    }

    for(int score: scores) {
        if(score < 0 || score > 100) {
            throw new IllegalArgumentException("Score is not valid!");
        }
        sum += score;
    }
    return sum/scores.length;
}

}

Mike Huang
  • 257
  • 1
  • 2
  • 10
  • 5
    ...and once the OP copy-pastes this answer and submits it, the entire point of the assignment would be moot and the OP would not learn anything from it. – K Mehta Apr 27 '12 at 03:14
  • Wow. When a question is tagged "homework", it's poor form to spoon-feed an answer. Read the [FAQ entry on meta](http://meta.stackexchange.com/questions/10811/how-to-ask-and-answer-homework-questions) about how to ask and answer homework questions. – Ted Hopp Apr 27 '12 at 03:15
  • 1
    Thank you. His post actually helped especially with everyone else input and help. I can see the differences between mine. And I had something similar in my book to this already. I just now need to add a catch and try and figure out how to do that correctly. Thanks everyone. – Alexandria Apr 27 '12 at 03:41
  • 1
    Somebody is supposed to learn how to program (it is an assignment). And learning is not transmitted by providing the answer, it is transmitted by providing hints (-1) – Oleg Sklyar Jan 10 '14 at 23:37
  • 2
    +1. I believe it is up to the student to learn the best they can; they should recognise that copy+pasting is a poor way to learn and that this answer is helpful for comparision to their attempt. I do not think this should be the accepted answer because it does not explain anything on it's own, but it compliments the other answers. – Caelum Apr 17 '16 at 12:00