This discussion is archived
1 2 3 Previous Next 44 Replies Latest reply: Dec 30, 2008 9:16 AM by 801510 RSS

Problem with storing values in an array in a for loop

801510 Newbie
Currently Being Moderated
I have an array of objects that i am trying to keep track of. Every time i iterate through the loop i add a newly created object to the array.
Problem-> whenever i display the array it always only shows the last record that was added when i want it to display every record in the whole array
i read the values from an xml file, i tried taking all that out so this is smaller

THE PROBLEM IS THE temp[] and person[s] arrays, i dont know if im doing that in the right place since when i output it it just saves the last value that was entered.

Ill post everything just in case theres something i missed, any help would be appreciated
     person=new Person[totalPeople];
     // normalize text representation
     for( s=0; s<listOfTests.getLength() ; s++)
     {
          personList.clear();
          
               for (int i = 0; i < nodes.getLength(); i++) 
               {
                    Element element = (Element) nodes.item(i);
                    String name = element.getAttribute("name");
                    String message = "From " + name + " tag: "+ "Training required : ";

                    // Process the lines

                    NodeList lines = element.getElementsByTagName("training");
                    temp=new Record[lines.getLength()];
                    for (int j = 0; j < lines.getLength(); j++) 
                    {
                         
                         Element line = (Element) lines.item(j);
                         if (j > 0)
                              message += ",";
                              message += " ";
                         
                              // Collect the text from the <Line> element

                              StringBuffer sb = new StringBuffer();
                              for (Node child = line.getFirstChild();child != null;child = child.getNextSibling())
                              {
                                   if (child instanceof CharacterData) 
                                   {
                                        CharacterData cd = (CharacterData) child;
                                        sb.append(cd.getData());
                                   }
                              }
                              String text = sb.toString().trim();
                              StringTokenizer token = new StringTokenizer(text);
                              
                               one =token.nextToken();
                               two =token.nextToken();
                               three =token.nextToken().toString();
                               recordList.add(new Record(one,two,three)); 
                               ArrayList random=new ArrayList();
                               message += text;
                               temp[j]=new Record(one,two,three);
                         
                               person[s]=new Person(firstName,lastName,status,recordList);      
                    }
                    
               
               }//end of original big for loop that WORKS!
               //persons[s]=new Person(firstName,lastName,status,temp);
          }//end if     
          
     
     }//end of for loop 

}catch (Exception e) {
// Do something with the exception
}

}

}
  • 1. Re: Problem with storing values in an array in a for loop
    796447 Newbie
    Currently Being Moderated
    Without seeing your Person class, it probably has a bunch of 'static' members. So every Person object shares the same properties. Just guessing. There isn't enough to go on as it stands right now.

    Edit:
    person[s]=new Person(firstName,lastName,status,recordList);
    I see you're doing this inside another loop, where 's' is held constant during the lifecycle of that loop. So you're throwing away everything except the last one created inside that loop.
  • 2. Re: Problem with storing values in an array in a for loop
    807589 Newbie
    Currently Being Moderated
    Post a SSCCE .
  • 3. Re: Problem with storing values in an array in a for loop
    DrClap Expert
    Currently Being Moderated
    I notice that the "recordList" variable seems to be accumulating Record objects for the entire program. You never clear it or reset it or anything like that. Maybe that's your problem.

    Your description of the actual problem isn't all that clear. For example you might have meant that you have an array of (say) 27 Person objects and all of those objects appear to have the same "first name" attribute. Or you might have meant something else. A more detailed problem description would help.

    (It would also help if your code was not indented so deeply. I shouldn't complain, at least you used the code tags and indented your code neatly which many people don't seem to be able to do. Thank you for doing that. But indenting two characters at a time rather than six or eight would mean that your code would all be visible at once, instead of scrolling off the right side of the screen.)
  • 4. Re: Problem with storing values in an array in a for loop
    801510 Newbie
    Currently Being Moderated
    hi, thanks for replying,
    yes i couldnt post all the code it said there was a limit so i cut out most of it so that part would fit, ill post the rest
    import java.util.LinkedList;
    import java.util.List;
    
    
    public class Person 
    {
         private static String firstName,lastName,status;
         private static List<Record> recordList;
         public Person(String firstName, String lastName, String status,List<Record> recordList) 
         {
              
                   this.firstName=firstName;
                   this.lastName=lastName;
                   this.status=status;
                   this.recordList= recordList;
                   
              
         }
         public String getFirstName()
         {
              return firstName;
         }
         public String getLastName()
         {
              return lastName;
         }
         public String getStatus()
         {
              return status;
         }
         public List<Record> getRecords()
         {
              return recordList;
         }
         public String toString()
         {
              String result="First name: " +firstName+ "\n";
              result+= "Last name " +lastName+ "\n";
              result+= "Status "+status+ "\n";
              result+= "Training required: "+recordList+ "\n";
              return result;
         }
    }
    public class Record 
    {
         protected String one;
         protected String two;
         protected String three;
         public Record(String one, String two, String three) 
         {
              super();
         }
    
         public String toString()
         {
              String result="One: " +one+ "\n";
              result+= "Two: " +two+ "\n";
              result+= "Three: "+three+ "\n";
              return result;
         }
    }
  • 5. Re: Problem with storing values in an array in a for loop
    807589 Newbie
    Currently Being Moderated
    private static String firstName,lastName,status;
    Ding!
  • 6. Re: Problem with storing values in an array in a for loop
    801510 Newbie
    Currently Being Moderated
    import java.io.File;
    import java.util.*;
    
    import javax.xml.parsers.*;
    
    import org.w3c.dom.*;
    import org.xml.sax.*;
    
    public class CreateRecords
    {
         
         static String firstName, lastName,status;
         public static int s,totalPeople;
         public static Person[] person;
         static String one,two,three;
         static Record []temp;
         static List<Record> recordList;
         static LinkedList<Person>personList;
         
         private CreateRecords()throws Exception
         {
              super();
              recordList=new ArrayList<Record>();
              personList=new LinkedList<Person>();
              
              
         }
         
    public static void loadFile()throws Exception
    {
         
    File file = new File("data.xml");
    try {
    
    // Parse the file
    
         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
         Document doc = builder.parse(file);
         
         doc.getDocumentElement ().normalize ();
         NodeList listOfTests = doc.getElementsByTagName("person");
         totalPeople = listOfTests.getLength();
         person=new Person[totalPeople];
         // normalize text representation
         for( s=0; s<listOfTests.getLength() ; s++)
         {
              personList.clear();
              Node firstSuiteNode = listOfTests.item(s);
              if(firstSuiteNode.getNodeType() == Node.ELEMENT_NODE)
              {
                   
                   Element firstSuiteElement = (Element)firstSuiteNode; 
    
                   //-------
                   NodeList fnameList = firstSuiteElement.getElementsByTagName("firstName");
                   Element fnameElement = (Element)fnameList.item(0);
    
                   NodeList textfNameList = fnameElement.getChildNodes();
                   firstName=((Node)textfNameList.item(0)).getNodeValue().trim();
         
                   //------- 
                   NodeList lnameList = firstSuiteElement.getElementsByTagName("lastName");
                   Element lNameElement = (Element)lnameList.item(0);
    
                   NodeList textlNameList = lNameElement.getChildNodes();
                   lastName=((Node)textlNameList.item(0)).getNodeValue().trim();
              
                   //----
                   NodeList statusList = firstSuiteElement.getElementsByTagName("status");
                   Element statusElement = (Element)statusList.item(0);
    
                   NodeList textRunList = statusElement.getChildNodes();
                   status=((Node)textRunList.item(0)).getNodeValue().trim();
                   //System.out.println("Name: "+name);
                   //System.out.println("lastName: "+lastName);
                   //System.out.println("status: "+status);
                            NodeList nodes = firstSuiteElement.getElementsByTagName("tag");
                   for (int i = 0; i < nodes.getLength(); i++) 
                   {
                        Element element = (Element) nodes.item(i);
                        String name = element.getAttribute("name");
                        String message = "From " + name + " tag: "+ "Training required : ";
    
                        // Process the lines
    
                        NodeList lines = element.getElementsByTagName("training");
                        temp=new Record[lines.getLength()];
                        for (int j = 0; j < lines.getLength(); j++) 
                        {
                             
                             Element line = (Element) lines.item(j);
                             if (j > 0)
                                  message += ",";
                                  message += " ";
                             
                                  // Collect the text from the <Line> element
    
                                  StringBuffer sb = new StringBuffer();
                                  for (Node child = line.getFirstChild();child != null;child = child.getNextSibling())
                                  {
                                       if (child instanceof CharacterData) 
                                       {
                                            CharacterData cd = (CharacterData) child;
                                            sb.append(cd.getData());
                                       }
                                  }
                                  String text = sb.toString().trim();
                                  StringTokenizer token = new StringTokenizer(text);
                                  
                                   one =token.nextToken();
                                   two =token.nextToken();
                                   three =token.nextToken().toString();
                                   recordList.add(new Record(one,two,three)); 
                                   ArrayList random=new ArrayList();
                                   message += text;
                                   temp[j]=new Record(one,two,three);
                             
                                   person[s]=new Person(firstName,lastName,status,recordList);      
                        }
                        
                   
                   }//end of original big for loop that WORKS!
                   //persons[s]=new Person(firstName,lastName,status,temp);
              }//end if     
              
         
         }//end of for loop 
    
    }catch (Exception e) {
    // Do something with the exception
    }
    
    }
    
    }
  • 7. Re: Problem with storing values in an array in a for loop
    807589 Newbie
    Currently Being Moderated
    BigDaddyLoveHandles wrote:
    private static String firstName,lastName,status;
    Ding!
    warnerja get's the cigar!
  • 8. Re: Problem with storing values in an array in a for loop
    807589 Newbie
    Currently Being Moderated
    Here is BigDaddy's Rule Of Static: Use static only for your main method (because you have to) and constants:
    public static final double PI = 3.141592653589793;
  • 9. Re: Problem with storing values in an array in a for loop
    801510 Newbie
    Currently Being Moderated
    and then the last part of it was the file
    but i think the file is ok right
    <?xml version="1.0"?>
    <record>
         <person>
              <firstName>Anne</firstName>
            <lastName>Wilson</lastName>
            <status>professor</status>
              <tag name="TrainingDescriptor" >
                   <training> monday, thursday, null </training>
                   <training> saturday, 11, 5</training>
                   <training> wednesday, friday, 9</training>
              </tag>
         </person>
         
         <person>
            <firstName>Sarah</firstName>
            <lastName>Tomas</lastName>
            <status>student</status>
             <tag name ="TrainingDescriptor" >
                   <training> monday, xp, 9 </training>
                   <training> wednesday, tuesday, null</training>
                   <training> saturday, 11, 5</training>
              </tag>
         </person>
    
         <person>
             <firstName>Angie</firstName>
             <lastName>Smith</lastName>
             <status>Trainer</status>
             <tag name ="TrainingDescriptor" >
                    <training>wednesday, tuesday, 5 </training>
              </tag>
         </person>
    </record>
  • 10. Re: Problem with storing values in an array in a for loop
    807589 Newbie
    Currently Being Moderated
    Encephalopathic wrote:
    BigDaddyLoveHandles wrote:
    private static String firstName,lastName,status;
    Ding!
    warnerja get's the cigar!
    Careful you don't set your mindreader's turban on fire when you light that.
  • 11. Re: Problem with storing values in an array in a for loop
    801510 Newbie
    Currently Being Moderated
    ohh ok thanks! ill change that static declaration, but would that be why only the last value is being kept?
  • 12. Re: Problem with storing values in an array in a for loop
    807589 Newbie
    Currently Being Moderated
    MissL wrote:
    ohh ok thanks! ill change that static declaration, but would that be why only the last value is being kept?
    that would be why there is one and only one value.
  • 13. Re: Problem with storing values in an array in a for loop
    807589 Newbie
    Currently Being Moderated
    Encephalopathic wrote:
    MissL wrote:
    ohh ok thanks! ill change that static declaration, but would that be why only the last value is being kept?
    that would be why there is one and only one value.
    Do you know the effect of declaring a field to be static?
  • 14. Re: Problem with storing values in an array in a for loop
    801510 Newbie
    Currently Being Moderated
    oh ok thanks, so then does it look like the person[s] is in the right spot inside the loop or...no?
1 2 3 Previous Next