gpt4 book ai didi

java - 如何在共享一个共同值的多个二维数组之间进行迭代?

转载 作者:行者123 更新时间:2023-12-01 13:28:23 26 4
gpt4 key购买 nike

如何在多个二维数组之间进行迭代。例如,我想查找居住在 Cobb、出生于 1970 年之后并且在 Evan Duggan 教授的类(class)中获得 C 或更好成绩的所有学生。这两个表共享用户 ID,例如“0033”

 public class JavaApplication2 {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String [ ][ ] students = {
{ "0033", "Sandra", "Smith", "Cobb", "1989" },
{ "1144", "Bo", "Harrison", "DeKalb","1987" },
{ "2255", "Sam", "Mitchell", "Cobb", "1969"},
{ "3366", "Sabrina", "Jones", "Cobb", "1979"},
{ "4477", "Harry", "Johnson", "Cobb", "1982"},
{ "5588", "Lisa", "Simpson", "Paulding", "1982"}
};

String[ ][ ] grades = {
{ "5588", "201405", "CSE", "1301J", "A", "Ian Salts" },
{ "5588", "201405", "COMM", "2400","B", "Evan Duggan" },
{ "5588", "201408", "CSE", "1302J", "A", "Ian Salts"},
{ "0033", "201405", "CSE", "1301J", "C", "Ian Salts"},
{ "0033", "201405", "COMM", "2400", "A", "Evan Duggan"}
};




for (int i = 0; i < students.length; i++)
{
System.out.print(students[ i ] [ 0 ] + ": ");
for (int j = 1; j < students[ i ].length; j++)
{
System.out.print(students[ i ][ j ] + " ");
}
System.out.println( );
}
System.out.println( );
for (int i = 0; i < grades.length; i++)
{
System.out.print(grades[ i ] [ 0 ] + ": ");
for (int j = 1; j < grades[ i ].length; j++)
{
System.out.print(grades[ i ][ j ] + " ");
}
System.out.println( );

}

for ( int i=0; i<grades.length; i++) {
for(int j=0; j< grades[i].length; j++) {
if ( grades[i][j].equals("A") && grades [i][5].equals("Evan Duggan")) {
System.out.println("The student ID is "+ grades[i][0]);

}
else if ( grades[i][j].equals("B") && grades [i][5].equals("Evan Duggan")){
System.out.println("The student ID is "+ grades[i][0]);
}
else if ( grades[i][j].equals("C") && grades [i][5].equals("Evan Duggan")){
System.out.println("The student ID is "+ grades[i][0]);
}

}


}

}
}

最佳答案

假设您必须使用二维数组,您可以通过分组和匹配与每个数组相关的条件来解决此问题:

for (String[] student: students) {
// First set of criteria relevant to students array
if (student[3].equals("Cobb") && Integer.parseInt(student[4]) > 1970) {

for (String[] grade: grades) {
// Match on student id as well as criteria relevant to grades array
if (grade[0].equals(student[0]) && grade[5].equals("Evan Duggan")) {

// I separate the conditionals here to keep it readable/tidy
// Consider using a Enum type or comparator etc.
if (grade[4].equals("C") || grade[4].equals("B") || grade[4].equals("A")) {
// Code for handling matching student
}
}
}
}
}

关于java - 如何在共享一个共同值的多个二维数组之间进行迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21691776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com