Iterate over two arrays simultaneously using for each loop in Java

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

How can 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 is to use an index variable in the same loop. Is there a good way?

+6
source share
3 answers

The main problem is that you have to link both arrays together and iterate over only one array.

Here is a VERY simplified demo - you should use getters and setters, and you should also use 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) { ... } 
+7
source

You need to do this using a regular for loop with index, for example:

 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 to use the class to store the student along with his / her signs, for example:

 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()); } 
+10
source

If they both are the same size, I would write:

 for(int i = 0; i<marks.length; i++) { String names= studentNames[i] int mark = marks[i]; } 
+4
source

Source: https://habr.com/ru/post/955766/


All Articles