About Java classes (1 Viewer)

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

18
0
I have only 1 day to work on my lab. Hope someone could help me as soon as possible.

My problem is I don't know how to count how many objects are created in a class.

The first assignment is write a Java class, Student, that has the following instance variables: name (String), age (int), gpa (double), courseGrades (array of char: A, B, C, D, F)

The class also has methods that would calculate the GPA of the student.
Then test the program by creating some objects: Student s1 = new Student(); .... blah...blah

And the second assignment, today my instructor just added it, is count how many objects are created in the class.


I just do a little like this :uhh:

Code:
public int getCount(){
        int count = 0;
        ................
        return count;
}
I don't know I could count it due to what things :frown:
 

dav2008

Bubble-Pipe Squirrel
Gold Member
607
1
From what I remember of Java you would want to create a static variable that gets incremented each time an instance of your object is created.
 
18
0
Oh yeah, today we were talking about static variables.
But what signal would be to indicate the object is created? :confused:
 

chroot

Staff Emeritus
Science Advisor
Gold Member
10,097
33
When an object is created, the class's constructor is called.

- Warren
 
18
0
I still don't get it. Can you give me some more clue?
 

chroot

Staff Emeritus
Science Advisor
Gold Member
10,097
33
The Student class has a method, also called Student, which is referred to as a constructor:

PHP:
publc class Student {
  public Student(...) {
    ...
  }
}
(If no constructor exists explicitly, an empty constructor is assumed).

Every time you execute a line of code that involves "new Student(...)", the constructor is called. The constructor can keep track of how many Student objects have been created by incrementing a counter (stored a class variable) each time it is run.

- Warren
 
18
0
PHP:
public class Student{
       private static int count = 0;

       public int getCount(Student s){
              if (s == new Student())
              count++;
       }
}
I don't think it would be correct :uhh:
I feel I still miss something, do I need a loop to go through the class to get all of objected that are created? :confused: So complex
 

chroot

Staff Emeritus
Science Advisor
Gold Member
10,097
33
No, that won't work. The expression s == new Student() will always evaluate to false.

You need to put your counter code in the CONSRUCTOR. Like this:

PHP:
public class Student {
    private static int count = 0;

    public Student() {
        count = count + 1;
    }

    public int getCount() {
        return count;
    }
}
- Warren
 
18
0
Oh, my!! I couldn't think in that way.

If I don't have a default constructor methods, can I conbine like this?
PHP:
public class Student{
	private String name;
	private int age;
	private double gpa;
	private char [] courseGrade;
	private static int count = 0;

	public Student(String name, int age){
		this.name = name;
		this.age = age;
		gpa = 0;
		courseGrade = null;
                count++;
	}
 
        public int getCount(){
                return count;
        }
        ................................
}

By the way, would you mind to look over my program?

PHP:
public class Student{
	private String name;
	private int age;
	private double gpa;
	private char [] courseGrade;
	private static int count = 0;

	public Student(String name, int age){
		this.name = name;
		this.age = age;
		gpa = 0;
		courseGrade = null;
	}

	public String getName(){
		return name;
	}

	public int getAge(){
		return age;
	}

	public double getGpa(){
		return gpa;
	}

        public int getCount(){
                return count;
        }

	public void setGrades(char [] grades){
		courseGrade = new char [grades.length];
		for (int i = 0; i < grades.length; i++){     // Problem seems here, I don't know how to create the courseGrades from null. Is that ok?
			courseGrade[i] = grades [i];
		}

		for (int i = 0; i < grades.length; i++){
			switch (grades[i]){
				case 'A': gpa += 4;
				break;
				case 'B': gpa += 3;
				break;
				case 'C': gpa += 2;
				break;
				case 'D': gpa += 1;
				break;
			}
			gpa /= grades.length;
		}
	}

	public String toString () {
		String tempString = "";
		tempString.format("Name: %s \n Age: %d \n GPA: %4.2f \n Grades: ",
		                                                  name, age, gpa);
		for (int i = 0; i < courseGrade.length; i++) {
			tempString += courseGrade [i] + ", ";
		}

		return tempString;
	}

	public static void main (String[]args){
		Student s1 = new Student ("Joe", 19);
		char grades1 [] = {'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B'};

		s1.setGrades(grades1);
		s1.getGpa();
		s1.toString();

		Student s2 = new Student("Mary", 20);
		char grades2 [] = {'A', 'A' , 'B', 'B', 'C', 'C', 'D', 'D', 'F', 'F'};
		s2.getGpa();
		System.out.println("Before calculating the GPA \n" + s2.toString());
		s2.setGrades(grades2);
		s2.getGpa();
		System.out.println("After calculating the GPA \n" + s2.toString());
	}
}
 

chroot

Staff Emeritus
Science Advisor
Gold Member
10,097
33
Yes, you've added "count++" to your constructor appropriately.

- Warren
 
18
0
I have one more question about static variable.
If I have an array:
PHP:
Student [] students = new Student [20];
and I have to write a method to create a Student object and put a reference to this student in the students array.

For each time adding one student, I have to know how many students have added in the students array, so I think I need one more variable
PHP:
int count;
to do this.

I think this variable would be static, right?
 

0rthodontist

Science Advisor
1,230
0
count probably should have the same visibility as your Student[] array. For example if your students array is a global static variable, that's what the count should be. If the students array is local and you pass it to the add student method, then you should also pass count to the add student method and have it return the new count. A good solution is to have a Students class that contains both the count and the students array, as well as the add student method. That way you do not have to keep track of count and students separately.

A better way would be to use a Vector<Student> (from package java.util.*). That will automatically report how many students are in it by the size() method and there is no limit on the number of students it can contain.
 

The Physics Forums Way

We Value Quality
• Topics based on mainstream science
• Proper English grammar and spelling
We Value Civility
• Positive and compassionate attitudes
• Patience while debating
We Value Productivity
• Disciplined to remain on-topic
• Recognition of own weaknesses
• Solo and co-op problem solving
Top