A true beginner here, I just started learning Java recently and I am trying to resolve an exercise where I should build arrays called grups (not bigger than 10) by using objects of another class and to always know the lenght of these groups that I have created.
Now, whenever I’m trying to return the value(lenght) of a group I seem to be getting the wrong result and I can’t figure it out why.
Here’s the code I’ve been writing:
package classes.school;
public class Group {
public static void main(String[] args) {
Student group1[] = new Student[]{};
group1 = new Student[10];
group1[0] = new Student("Johny", 'm', true);
group1[1] = new Student("Pete", 'm', false);
group1[2] = new Student("Alice", 'f', false);
group1[3] = new Student("Julie", 'f', true);
group1[4] = new Student("Romeo", 'm', false);
group1[5] = new Student("Marion", 'm', true);
group1[6] = new Student("Aaron", 'm', true);
group1[7] = new Student("Alex", 'm', true);
group1[8] = new Student("Monica", 'f', false);
group1[9] = new Student("Sonia", 'f', false);
int group1Length = 0;
for (int i = 0; i < group1.length; i++) {
group1Length += i;
}
System.out.println("The number of students in Group 1 is: " + group1Length);
}
}
And here’s the return:
The number of students in Group 1 is: 45
Any suggestions of what shoud I be looking into? I’m not sure where 45 would come from since the lenght of my array is 10.
Thanks a lot! 🙂
>Solution :
for (int i = 0; i < group1.length; i++) {
// group1Length += i;
group1Length++;
}
of it’s better to have:
int group1Length = group1.length;