AmandaRJ AmandaRJ - 2 months ago 7
Java Question

print on the screen a repeat loop

I have a repeating structure in my Java class and wanted to present the data as follows:

Peter Black
John Red


I do not know if the structure is right, because if I leave to show the color only, the data is overwritten

public class Test {

public static void main(String[] args) {
List<Person> persons = new ArrayList<>();

String[] names= {"Peter", "John"};
String[] colors= {"Black", "Red"};

for (String name: names) {
Person d = new Person();

d.setName(name);

for (String color: colors) {
d.setColor(color);
}
persons.add(d);
}

for (Person a : persons) {
System.out.println(a.getName() + "-" + a.getColor());
}
}
}


Console:

Peter-Red
John-Red

Answer

Instead of using a nested for loop, which is not what you are trying to accomplish, loop through both arrays at the same time.

if (names.length != colors.length) {
    // error! not a 1:1 relationship
    return;
}
for (int i = 0; i < names.length && i < colors.length; i++) {
    String name = names[i], color = colors[i];
    Person d = new Person();
    d.setName(name);
    d.setColor(color);
    persons.add(d);
}

I could just do i < names.length, however that will break if both arrays are different sizes, so i < names.length && i < colors.length will make sure i never exceeds either of the two arrays' lengths.

Edit: I think the real problem here is how you are storing your info. Why are you using two string arrays, instead of a collection containing Person objects?