14 Replies Latest reply: Oct 19, 2007 9:39 PM by 807603 RSS

    Storing in an array from my own created class

    807603
      Hi,
      Here I am again with more questions. I am grovelling for help.
      I am working on a program in Netbeans 5.5.1 where I created a class called Student that gets and sets Last Name, First Name and Student ID. Now the program to run as a samle of this class will store the first Student I get and put it into slot [0] of my array and then I increment my NumStudents, as a count to moveon to the next array slot. The problem is that it only puts the Student info into slot[0], even on the 2nd or 3rd entry to store information. I'm not sure if the problem is in the gets and sets in my class or in my Store Info button listener.
      Here is a bit of the code. I have comments to help explain my problem.

      Thank you oh virtuosos of Java! This stuff brings me to tears!


      private void mouseclickedbtnStoreInfo(java.awt.event.MouseEvent evt)
      {
      // Code to store info from the textbox entered by user:


      s.setFirstName(txtFirstName.getText());

      s.setLastName(txtLastName.getText());

      s.setStudentID(txtStudentID.getText());

      arrayAllStudents[NumStu] = s;
      NumStu++;

      txtFirstName.setText("");
      txtLastName.setText("");
      txtStudentID.setText("");

      //Testing array storage here also

      /*This only prints out only for the second student entered, loses the first, NumStu times, apparently only storing in slot 0. array is of Student class as is the variable s.*/

      for(int i=0;i<NumStu;i++){
      System.out.println(arrayAllStudents.getStudentID());
      System.out.println(arrayAllStudents[i].getFirstName());
      System.out.println(arrayAllStudents[i].getLastName());
      }

      }

      Hopefully this is not a challenging puzzle for all you experts out there. Pop me a line soon. I'll take my turn helping when I get this #*@& figured out.
        • 1. Re: Storing in an array from my own created class
          807603
          Please use the code formatting tags when you post code (use the code button) as they prevent the italic mangling as is going on here.

          I think you'll need to repost your code as it is unreadable and we can't really guess where you are accessing what and how of your array.

          I would ask a somewhat obvious question though and that is is there a reason you can't use a Collection like a List of some sort? That would make life easier for you although you may not be allowed to do as a requirement of your homework.. I don't know.
          • 2. Re: Storing in an array from my own created class
            807603
            private void mouseclickedbtnStoreInfo(java.awt.event.MouseEvent evt) 
            { 
            // Code to store info from the textbox entered by user:
            
            
            s.setFirstName(txtFirstName.getText()); 
            
            s.setLastName(txtLastName.getText());
            
            s.setStudentID(txtStudentID.getText());
            
            arrayAllStudents[NumStu] = s;
            NumStu++;
            
            txtFirstName.setText("");
            txtLastName.setText("");
            txtStudentID.setText("");
            
            //Testing array storage here also 
            
            /*This only prints out only for the second student entered, loses the first, NumStu times, apparently only storing in slot 0. array is of Student class as is the variable s.*/
            
            for(int i=0;i<NumStu;i++){
            System.out.println(arrayAllStudents.getStudentID());
            System.out.println(arrayAllStudents.getFirstName());
            System.out.println(arrayAllStudents.getLastName()); 
            }
            
            }
            I tried the CODE button. I hope that helps. My professor suggested using an array of Students, but I think she would be open to using a List. I have not learned about this yet, though. What does that entail?
            Would you like me to clarify anything else?
            • 3. Re: Storing in an array from my own created class
              807603
              Are you sure that this line
              NumStu++;
              is actually what you have in your code and not something like?
              NumStu = NumStu++;
              Otherwise I would print out the value of NumStu in various places and see what you have. If you haven't made the above mistake then it would seem you are resetting this value elsewhere. Or something else is being reset...


              As far as Lists go see this http://java.sun.com/docs/books/tutorial/collections/index.html
              • 4. Re: Storing in an array from my own created class
                807603
                I have done a print out on NumStu to check if it is actually incrementing an it is. In fact, the for loop will print out NumStu times the last Student entered.
                1111
                John
                Jones
                (all this, 3 times if NumStu is 3)

                Looking at the list method, I believe I need to use a Student object, not a list object to retrieve from my Student class. I'll look more at this tutorial, but that is how I understood my professor. Am I wrong?
                • 5. Re: Storing in an array from my own created class
                  807603
                  PrairieChicken wrote:
                  I have done a print out on NumStu to check if it is actually incrementing an it is. In fact, the for loop will print out NumStu times the last Student entered.
                  1111
                  John
                  Jones
                  (all this, 3 times if NumStu is 3)
                  Actually I don't understand how this even compiles
                  for(int i=0;i<NumStu;i++){
                  System.out.println(arrayAllStudents.getStudentID());
                  System.out.println(arrayAllStudents.getFirstName());
                  System.out.println(arrayAllStudents.getLastName()); 
                  }
                  If arrayAllStudents is an array I can't see how it can be...

                  Did you lose some [ ] when you reposted? I think so.

                  Try repasting your original code (with the formatting) don't copy and paste the code from your first post because the forum already screwed it up.


                  >
                  Looking at the list method, I believe I need to use a Student object, not a list object to retrieve from my Student class. I'll look more at this tutorial, but that is how I understood my professor. Am I wrong?
                  • 6. Re: Storing in an array from my own created class
                    807603
                    O.k. I'll try this again. We'll see if anything is clearer with this code. Before this I also have automatically generated code from Netbeans coding my gui. I also have another page of code generating my Student.class. The only methods I have in that are the sets and gets of StudentID, LastName, and FirstName.

                        private void mouseclickedbtnStoreInfo(java.awt.event.MouseEvent evt) {                                          
                    // Code to store info from the textbox entered by user:
                            
                            
                            s.setFirstName(txtFirstName.getText()); 
                                 
                            s.setLastName(txtLastName.getText());
                                  
                            s.setStudentID(txtStudentID.getText());
                            
                            arrayAllStudents[NumStu] = s;
                            NumStu++;
                            
                            txtFirstName.setText("");
                            txtLastName.setText("");
                            txtStudentID.setText("");
                            
                            //Testing array storage here also 
                           
                            //This only prints out only for the second student entered and loses the first NumStu times
                            for(int i=0;i<NumStu;i++){
                                System.out.println(arrayAllStudents.getStudentID());
                    System.out.println(arrayAllStudents[i].getFirstName());
                    System.out.println(arrayAllStudents[i].getLastName());
                    }






                    }

                    private void mouseClickedRetrieveInfo(java.awt.event.MouseEvent evt) {                                         
                    // Code for user to retrieve the info from textboxes:

                    //This is all printing out as only the last student entered but as many times as Num##.

                    for(int i=0;i<NumStu;i++){
                    System.out.println(arrayAllStudents[i].getStudentID());
                    System.out.println(arrayAllStudents[i].getFirstName());
                    System.out.println(arrayAllStudents[i].getLastName());
                    }



                    }


                    /**
                    * @param args the command line arguments
                    */
                    public static void main(String args[]) {
                    java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                    new frmTestStudentClass().setVisible(true);
                    }
                    });
                    }

                    // Variables declaration - do not modify
                    private javax.swing.JButton btnRetrieveInfo;
                    private javax.swing.JButton btnStoreInfo;
                    private javax.swing.JLabel lblFirstName;
                    private javax.swing.JLabel lblLastName;
                    private javax.swing.JLabel lblStudentID;
                    private javax.swing.JTextField txtFirstName;
                    private javax.swing.JTextField txtLastName;
                    private javax.swing.JTextField txtStudentID;
                    // End of variables declaration
                    Student s;
                    Student arrayAllStudents[] = new Student[MaxStu];
                    }
                    This does compile and run the gui. User can enter text into the textboxes and when I hit my StoreInfo button the textboxes clear and NumStu is incremented and first entrance is stored in arrayAllStudents[0].  This seemed to paste just as it is in Netbeans.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
                    • 7. Re: Storing in an array from my own created class
                      807603
                      Finally I see the light.

                      s is a class variable. Which isn't really desirable. More importantly though you never re initialize it.

                      So what's happening is this.

                      1) You create a Student object

                      2) You set values of the student object using the acccessor methods

                      3) You add the student object to the array

                      4) GOTO 2

                      So it is the same object you are adding each time. In other words the Student array is filled with references to the same object. When you change the values of the object since they are all the same object it changes in all of them.

                      To solve:

                      rip out s as a class variable.

                      In your adding method make the first line be
                      Student s = new Student();
                      Please also note that this will require the fields storing the first and last names and id to be non-static. The method setFirstName etc must also be non-static. I have a bad feeling they are static too. So that will have to change.
                      • 8. Re: Storing in an array from my own created class
                        807603
                        Here is my code from my class Student. They aren't static, but I wish that was an easy fix.
                        Also, I have my Student s initialized up in my init components that I didn't send you.
                        Here is the first section of my code that I had left out.

                        public class frmTestStudentClass extends javax.swing.JFrame {
                        public frmTestStudentClass() {
                                initComponents();
                                s = new Student(); 
                                
                                
                            }
                                int NumStu = 0;
                                int MaxStu = 30;  
                        Here is my Student class:
                        public class Student {
                            private String LastName;
                            private String FirstName;
                            private String StudentID;
                            
                            
                            
                            /** Creates a new instance of Student */
                            public Student() {
                            }
                            
                        
                           
                        
                            public Student(String tmpLastName, String tmpFirstName, String tmpStudentID) {
                                  tmpLastName = "";
                                  tmpFirstName = "";
                                  tmpStudentID = "";
                            }
                        
                            public String getLastName() {
                                return LastName;
                            }
                        
                            public void setLastName(String LastName) {
                                this.LastName = LastName;
                            }
                        
                            public String getFirstName() {
                                return FirstName;
                            }
                        
                            public void setFirstName(String FirstName) {
                                this.FirstName = FirstName;
                            }
                        
                            public String getStudentID() {
                                return StudentID;
                            }
                        
                            public void setStudentID(String StudentID) {
                                this.StudentID = StudentID;
                            }
                            
                        }
                        • 9. Re: Storing in an array from my own created class
                          807603
                          Okay well the non-static is good but the other things I said still apply.

                          You only ever have one Student instance. That is wrong. You need a new Student instance every time you want to add a new Student. Not re-using the same student over and over again.

                          So again at the beginning of the method that adds do this...
                          Student s = new Student();
                          Then it will work. It's really that simple.
                          • 10. Re: Storing in an array from my own created class
                            807603
                            Did I stump you or frustrate you? Sorry about the back and forth or leaving things out. I didn't want to burden you with extra code at first, but that theory just seems more confusing than just seeing what I've got.
                            Here is my run output after user entering 2 names and IDs. Of course take into consideration that I have an extra for loop just for error checking in my StoreInfo action:

                            init:
                            deps-jar:
                            compile:
                            255551
                            Jon
                            Jones
                            46464
                            Bob
                            Smith
                            46464
                            Bob
                            Smith
                            46464
                            Bob
                            Smith
                            46464
                            Bob
                            Smith
                            debug:
                            BUILD SUCCESSFUL (total time: 40 seconds)
                            • 11. Re: Storing in an array from my own created class
                              807603
                              Did you try what I said?
                              • 12. Re: Storing in an array from my own created class
                                807603
                                I put the new Student inside the btnStoreInfo, just like you said (I got your message just as I sent mine). Wow. Thank you! So can you give me one more explanation of why this works this way just so I retain something more than simple stuff someday. I appreciate your help so much!
                                • 13. Re: Storing in an array from my own created class
                                  807603
                                  Okay well I tried to explain it a bit before but I'll try a different way. If this doesn't help let me know and I'll try again (although once I finish this post I am going for dinner so I'll be away for a bit).

                                  When you do this
                                  Student s = new Student();
                                  what is s exactly?

                                  Your first instinct might be to say that it is a Student object. But that isn't really correct. s is a variable that is a reference to an instance of a Student object.

                                  As an analogy what is a hat?

                                  The word hat is in fact not an actual hat. It's just a word. But it's a word that means an actual hat. So one could sort of say that they word hat is a reference to an actual hat.

                                  Now that we have that covered we need to look at what the array of Students actually holds. It doesn't hold actual Student objects. It holds references to Student objects.

                                  So where you were going wrong is that you were changing your Student object each time but you were always using the same reference to a Student object (aka the Student object was being used over and over again). Your array did hold multiple values, however the values were all the same reference to the same object.

                                  If I have now confused the hell out of you, or even if luckily I haven't, you should read this

                                  http://www.javaranch.com/campfire/StoryCups.jsp

                                  It's a well known and good explanation of variables, values and references in Java and can help clear it up for you.
                                  • 14. Re: Storing in an array from my own created class
                                    807603
                                    This does make some sense. I've had this whole objects and instances of a class explained to me many times. It does seem to soak in more every time, but the data flow and storage part of it gets jumbled up.

                                    Have a great dinner! Thanks for your help. I wish my professor could explain things that well.