我需要搜索一个数组并找到某个值,如果存在则返回 true,如果不存在则返回 false。
数组:
private String zonaDeInternamento[][][] = {
{
{"Livre", "Livre", "Livre", "Livre"},
{"Livre", "Livre", "Livre", "Livre"},
{"Livre", "Livre", "Livre", "Livre"},
{"Livre", "0012", "Livre", "Livre"},
{"Livre", "Livre", "Livre", "Livre"}
},
{
{"Livre", "0013", "Livre", "Livre"},
{"Livre", "Livre", "Livre", "Livre"},
{"Livre", "Livre", "Livre", "Livre"},
{"Livre", "Livre", "Livre", "Livre"},
{"Livre", "Livre", "Livre", "Livre"}
}
};
所以,如果搜索找到其中一个数字,则返回 true,如果找到“Livre”,则返回 false;
public boolean isPacienteInternado(String numeroProcesso) {
if (isNumeroProcessoValido(numeroProcesso)) {
for (int i = 0; i < zonaDeInternamento.length; i++) {
for (int j = 0; j < zonaDeInternamento[i].length; j++) {
for (int h = 0; h < zonaDeInternamento[i][j].length; h++) {
if ((zonaDeInternamento[i][j][h].equals(numeroProcesso))) {
System.out.println("O paciente com número de processo " + numeroProcesso + " está internado!");
return true;
} else {
System.out.println("O paciente com número de processo " + numeroProcesso + " não está internado!");
return false;
}
}
}
}
}
return false;
}
它一直返回 false,从不进入 if 语句,返回 else 消息和 false。当 numeroProcesso 为 13 或 12 时,运行 debug if ((zonaDeInternamento[i][j][h].equals(numeroProcesso))) 返回 false。我缺少什么?
最佳答案
public boolean isPacienteInternado(String numeroProcesso) {
if (isNumeroProcessoValido(numeroProcesso)) {
for (int i = 0; i < zonaDeInternamento.length; i++) {
for (int j = 0; j < zonaDeInternamento[i].length; j++) {
for (int h = 0; h < zonaDeInternamento[i][j].length; h++) {
if ((zonaDeInternamento[i][j][h].equals(numeroProcesso))) {
System.out.println("O paciente com número de processo " + numeroProcesso + " está internado!");
return true;
}
}
}
}
}
return false;}
关于java - 在多维数组中搜索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27306488/