Iterating over two arrays simultaneously using for each loop in Java

前端 未结 4 461
再見小時候
再見小時候 2020-12-16 05:45

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 ? <

相关标签:
4条回答
  • 2020-12-16 05:58

    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());
    }
    
    0 讨论(0)
  • 2020-12-16 06:03

    The other way is to use a verbose for loop statement such as;

    int i,j;
    for(i = 0, j=0; i<= student.length-1 && j <=grades.length-1; i++,j++)
    {
    ...
    }
    
    0 讨论(0)
  • 2020-12-16 06:11

    If them both have the same size, I would write:

    for(int i = 0; i<marks.length; i++) {
        String names= studentNames[i]
        int mark = marks[i];     
    
    }
    
    0 讨论(0)
  • 2020-12-16 06:21

    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) {
      ...
    }
    
    0 讨论(0)
提交回复
热议问题