如果找不到我输入的数据,我想进行处理。但是,当找不到数据时,程序将打印一条消息,否则将重复多次。我应该在哪里正确放置else语句?
public void Data(String x){
for (int i = 1; i < 6; i++) {
if (x.equalsIgnoreCase(table1[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table1[i][j]);
}
}
else if (x.equalsIgnoreCase(table2[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table2[i][j]);
}
}
else if (x.equalsIgnoreCase(table3[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table3[i][j]);
}
}
else if (x.equalsIgnoreCase(table4[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table4[i][j]);
}
}
else if (x.equalsIgnoreCase(table5[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table5[i][j]);
}
}
else if (x.equalsIgnoreCase(table6[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table6[i][j]);
}
}
else if (x.equalsIgnoreCase(table7[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table7[i][j]);
}
}
else System.out.println("Data not found!");
}
}
最佳答案
尝试这个:
public void Data(String x){
boolean b = false;
for (int i = 1; i < 6; i++) {
if (x.equalsIgnoreCase(table1[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table1[i][j]);
}
}
else if (x.equalsIgnoreCase(table2[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table2[i][j]);
}
}
else if (x.equalsIgnoreCase(table3[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table3[i][j]);
}
}
else if (x.equalsIgnoreCase(table4[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table4[i][j]);
}
}
else if (x.equalsIgnoreCase(table5[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table5[i][j]);
}
}
else if (x.equalsIgnoreCase(table6[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table6[i][j]);
}
}
else if (x.equalsIgnoreCase(table7[i][1])){
for (int j = 0; j < 4; j++) {
System.out.printf("|%-40s", table7[i][j]);
}
}
else b = true;
}
if (b) System.out.println("Data not found!");
}
关于java - Java-将else语句放入循环中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42896384/