Help with Counting Objects Created in a Java Class

In summary: Grade); return tempString; }}In summary, the student has to create a counter to track how many objects are created, and place that counter in the constructor.
  • #1
lypaza
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:
 
Physics news on Phys.org
  • #2
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.
 
  • #3
Oh yeah, today we were talking about static variables.
But what signal would be to indicate the object is created? :confused:
 
  • #4
When an object is created, the class's constructor is called.

- Warren
 
  • #5
I still don't get it. Can you give me some more clue?
 
  • #6
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
 
  • #7
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
 
  • #8
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
 
  • #9
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());
	}
}
 
  • #10
Yes, you've added "count++" to your constructor appropriately.

- Warren
 
  • #11
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?
 
  • #12
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.
 

1. How can I count the objects created in a Java class?

To count the objects created in a Java class, you can create a static variable within the class and increment it every time an object is created. This variable will keep track of the total number of objects created.

2. Can I use a loop to count the objects created in a Java class?

Yes, you can use a loop to iterate through the objects created in a Java class and count them. However, this might not be the most efficient way as it requires extra code and may impact the performance of your program.

3. How can I access the total number of objects created in a Java class?

You can access the total number of objects created in a Java class by either using a getter method for the static variable that counts the objects, or by directly accessing the variable if it is public.

4. Is there a built-in method in Java to count objects created in a class?

No, there is no built-in method in Java to count the objects created in a class. You will need to implement your own logic to keep track of the number of objects created.

5. Can I reset the count of objects created in a Java class?

Yes, you can reset the count of objects created in a Java class by setting the static variable that counts the objects to 0. However, this will only reset the count for the current instance of the class and will not affect any previous instances.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
12
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
6K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
11
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
15
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
Back
Top