Pjayness
Pjayness

Reputation: 365

Trying to run two double for loops

So I have two array lists:

ArrayList<String> name = getNames();
ArrayList<String> comment = getComments();

And I have an object named feedback which contains two parameters: name and comment to which I'm storing all the names and comments existing in the arraylists mentioned above.

ArrayList<feedback> fb = new ArrayList<feedback>();

    for(int i=0;i<name.size();i++)
    {
      for(int j=0;j<comment.size();j++)
      {
         feedback f = new feedback();
         f.name = name.get(i).toString();
         f.comment = comment.get(j).toString();
         fb.add(f);
      }
    }

What I want is to store these names and comments in order respectively such that the first name will be assigned the first comment. Instead what I get is every name being assigned to every comment.

What I want:

For example:

Bill added a comment: "Hey"
Jerry added a comment: "Oops"

So there should be 2 feedback objects:

Name = Bill
Comment = "Hey"

Name = "Jerry"
Comment: "Oops"

My loop is obviously wrong. What changes should I make?

Upvotes: 2

Views: 38

Answers (1)

Eran
Eran

Reputation: 393811

You need a single loop :

for(int i=0;i<name.size() && i < comment.size();i++) {
     feedback f = new feedback();
     f.name = name.get(i);
     f.comment = comment.get(i);
     fb.add(f);
}

Upvotes: 4

Related Questions