This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Posted by Chet Underwood, Esq. on December 16, 2001 at 1:53 PM
> > 1. Define a java class called student. Each student has a name, a count of taken exams, and an average grade in those exams. At the beginning of the semester, we start with a count of 0 exams & an average of 0.
> > The class should have [at least] 3 methods, plus of the constructor:
> > � GetName : To simply return the student�s name
> > � GetAverage: To return the student�s average grade so far
> > AddTest: to add a new test score to the student�s record.
> aight ...
"aight?" Is this the cool hip-hop way of spelling "alright?" You need to spend fewer of those precious brain cells trying to be cool and free them up for working on your homework assignments. Okay, enough editorializing.
As for your halfhearted attempt at doing your homework:
- The convention in Java is to capitalize the first letter of a class name.
- Where is the constructor? It should set the Student's name.
- Your assignment may have said "a constructor and three methods," but I'm sure it meant "at least three methods." To do a good job on this thing, you need more than three methods.
- Why are methods prefixed get doing set operations? They should only return information. There should be complimentary set methods, where appropriate.
- The getAverageScore() method should return a calculated result, based on the sum of test scores divided by the number of tests.
- addTest() needs to actually add a test, not just set a local variable. This means you need to have an array, or a List defined in your class (not in the method) and add test results to it.
- It might be more flexible to have a TestResult object (especially if your teacher is going to have you embellish this assignment in future assignments). The TestResult object could then contain information like the name of the test, the score and the weight.
- Things which are state information for the object and need to last outside the scope of a single method should be instance data. For example:
public class Student
List testResults = new ArrayList();
public Student( String name )
this.name = name;
public void addTestResult( TestResult r )
public String getName()
Iterator i = testResults.iterator();
int count = 0;
int sum = 0;
while( i.hasNext() )
sum += ((TestResult)i.next()).getScore();
return count > 0 ? sum / count : count;
You'll have to create the TestResults class. You could also use
float where I have
- It is also not a bad idea to create a main() for testing purposes (I made a little TestResults class whose default constructor generated a random score, then a main() with a loop that added a bunch of these to a Student object to test it out).