Scanner input = new Scanner(System.in);
int numInput;
int number[][] = {
{10, 20, 30},
{15, 25, 35},
};
System.out.print("\n\tEnter a Number : ");
// Expected input 10
numInput = input.nextInt();
input.nextLine();
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
if (numInput == number[i][j]) {
System.out.print("\n\tNumber " + numInput + " Found!");
System.out.print("\n\tOn line " + i + " Column " +j);
} else {
System.out.print("\n\tNumber Not Found!");
}
}
}
如果用户输入 35,该程序将打印“Number 35 Found!”对于在数组中找到的数字或“未找到数字!”对于数组中的每个其他元素。
我希望它只打印一次。
最佳答案
看起来您需要将“Number not Found”的打印语句移到 for 循环之外。像这样:
Scanner input = new Scanner(System.in);
int numInput;
int number[][] = { {10, 20, 30},
{15, 25, 35},
};
System.out.print("\n\tEnter a Number : ");
//Expected input 10
numInput = input.nextInt();
input.nextLine();
boolean found = false;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
if (numInput == number[i][j]) {
found = true;
System.out.print("\n\tNumber " + numInput + " Found!");
System.out.print("\n\tOn line " + i + " Column " +j);
}
}
}
if (!found) {
System.out.print("\n\tNumber Not Found!");
}
按照您现在的方式,对于每个项目,它总是会打印“找到”或“未找到”。但是,如果您只想在最后打印一次,则需要某种标志来确定是否找到它,如果没有找到,则打印。
关于java - 如何在迭代多维数组后仅打印一次消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59721707/