1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

About Java classes

  1. Apr 17, 2006 #1
    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 (Text):
    public int getCount(){
            int count = 0;
            ................
            return count;
    }
    I don't know I could count it due to what things :frown:
     
  2. jcsd
  3. Apr 17, 2006 #2

    dav2008

    User Avatar
    Gold Member

    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.
     
  4. Apr 17, 2006 #3
    Oh yeah, today we were talking about static variables.
    But what signal would be to indicate the object is created? :confused:
     
  5. Apr 17, 2006 #4

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    When an object is created, the class's constructor is called.

    - Warren
     
  6. Apr 17, 2006 #5
    I still don't get it. Can you give me some more clue?
     
  7. Apr 17, 2006 #6

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    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
     
  8. Apr 17, 2006 #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
     
  9. Apr 17, 2006 #8

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    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
     
  10. Apr 17, 2006 #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());
        }
    }
     
  11. Apr 17, 2006 #10

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Yes, you've added "count++" to your constructor appropriately.

    - Warren
     
  12. May 3, 2006 #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?
     
  13. May 5, 2006 #12

    0rthodontist

    User Avatar
    Science Advisor

    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: About Java classes
  1. Java class Arrays (Replies: 1)

Loading...