Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over two arrays simultaneously using for each loop in Java

Tags:

java

foreach

Student's names(String[]) and corresponding marks(int[]) are stored in different arrays.

How may I iterate over both arrays together using for each loop in Java ?

void list() {

    for(String s:studentNames) {
        System.out.println(s); //I want to print from marks[] alongside.
    }
}

One trivial way could be using index variable in the same loop. Is there a good way to do?

like image 800
dev Avatar asked Oct 11 '13 12:10

dev


2 Answers

You need to do it using the regular for loop with an index, like this:

if (marks.length != studentNames.length) {
    ... // Something is wrong!
}
// This assumes that studentNames and marks have identical lengths
for (int i = 0 ; i != marks.length ; i++) {
    System.out.println(studentNames[i]);
    System.out.println(marks[i]);
}

A better approach would be using a class to store a student along with his/her marks, like this:

class StudentMark {
    private String name;
    private int mark;
    public StudentMark(String n, int m) {name=n; mark=m; }
    public String getName() {return name;}
    public int getMark() {return mark;}
}

for (StudentMark sm : arrayOfStudentsAndTheirMarks) {
    System.out.println(sm.getName());
    System.out.println(sm.getMark());
}
like image 113
Sergey Kalinichenko Avatar answered Oct 01 '22 19:10

Sergey Kalinichenko


The underlying problem is actually that you should tie both of the arrays together and iterate across just one array.

Here is a VERY simplistic demonstration - you should use getters and setters and you should also use a List instead of an array but this demonstrates the point:

class Student {
  String name;
  int mark;
}
Student[] students = new Student[10];

for (Student s : students) {
  ...
}
like image 33
OldCurmudgeon Avatar answered Oct 01 '22 20:10

OldCurmudgeon