我有一系列名字、姓氏、ID 和电子邮件。我的用户将输入名字和姓氏,如果在数组中找到,它应该打印所有信息(名字、姓氏、ID 和电子邮件)。
我已经完成了我的代码,但它永远无法打印信息。总是说找不到信息。我想这是一个
{}
问题,但我无法解决这个问题。
这是我的代码:
static void liste1etudiant(String listetudiants0[][]) {
Scanner sc0 = new Scanner(System.in);
int i = 0, j = 0;
String prenom, nom;
boolean foundp = false, foundn = false;
System.out.println("Entrez le prenom de l'etudiant a chercher");
prenom = sc0.next();
System.out.println("Entrez le nom de l'etudiant a chercher");
nom = sc0.next();
for (j = 0; j < listetudiants0.length; j++) {
if (listetudiants0[j][i].equalsIgnoreCase(prenom)) {
foundp = true;
}
if (foundp) {
for (i = 0; i < listetudiants0[0].length; i++) {
if (listetudiants0[j][i].equalsIgnoreCase(nom)) {
foundn = true;
}
}
}
}
if (foundn) {
System.out.println(listetudiants0[j][i]);
} else {
System.out.println("The student is not in the table");
}
}
对于此问题,您应该使用 AND 运算符 (
&&
)。
有了这个,您可以立即检查姓名和姓氏。多亏了这一点,您将能够摆脱
foundp
和 foundn
,只有一个 found
变量和一个循环。
您还可以使用
break
关键字提前结束循环,这样一找到人就停止循环。
static void liste1etudiant(String listetudiants0[][]) {
Scanner sc0 = new Scanner(System.in);
int i = 0;
String prenom, nom;
boolean found = false;
System.out.println("Entrez le prenom de l'etudiant a chercher");
prenom = sc0.next();
System.out.println("Entrez le nom de l'etudiant a chercher");
nom = sc0.next();
for (i = 0; i < listetudiants0.length; i++) {
if (listetudiants0[i][0].equalsIgnoreCase(prenom) &&
listetudiants0[i][1].equalsIgnoreCase(nom)) {
found = true;
break;
}
}
if (found) {
System.out.println(listetudiants0[i][0]);
} else {
System.out.println("The student is not in the table");
}
}
PS:在 StackOverflow 上发帖时,你应该尝试隔离问题并用英文翻译所有内容😉