[英]How do I print a message only once after iterating through a multidimensional array?
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,該程序將打印“找到 35 號!” 對於在數組中找到的數字或“未找到數字!” 對於數組中的每個其他元素。
我希望它只打印一次。
看起來您需要將“未找到數字”的打印語句移到 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!");
}
按照您現在的方式,它總是會為每個項目打印“找到”或“未找到”。 但是如果你只希望它在最后打印一次,你需要有某種標志來確定它是否被找到,如果沒有,則打印。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.