我在测试应用程序时发现了一个小问题。我需要有一行代码运行以通知用户他们输入了无效的产品代码。
我遇到的问题是我不能简单地将它放在For 循环内的Else语句中,因为它会在每次产品代码不匹配时运行,直到找到匹配的代码,从而使其多次运行.
任何帮助将不胜感激,谢谢:)
static void searchProduct() {
System.out.print("Please enter product code to search: ");
String searchTerm = in.nextLine().toUpperCase();
for (int i = 0; i < report.size(); i++) {
if (report.get(i).code.equals(searchTerm)) {
System.out.println("****************************************************************************"
+ "\nPRODUCT SEARCH RESULTS"
+ "\n****************************************************************************");
System.out.println("PRODUCT CODE >> " + report.get(i).code);
System.out.println("PRODUCT NAME >> " + report.get(i).name);
System.out.println("PRODUCT CATERGORY >> " + report.get(i).category);
System.out.println("PRODUCT WARRANTY >> " + report.get(i).warranty);
System.out.println("PRODUCT PRICE >> " + report.get(i).price);
System.out.println("PRODUCT LEVEL >> " + report.get(i).stock);
System.out.println("PRODUCT SUPPLIER >> " + report.get(i).supplier);
System.out.println("****************************************************************************");
}
else {
// System.out.println("The product cannot be located. Invalid Product");
}
}
System.out.println("Enter (1) to launch menu or any other key to exit");
String opt2 = in.nextLine();
if (opt2.equals("1")) {
mainMenu.Menu();
}
else { System.exit(0); }
}
将打印与循环分开:
循环遍历列表,直到找到该项目:
Report r = null;
for (int i = 0; i < report.size(); ++i) {
if (report.get(i).code.equals(searchTerm)) {
r = report.get(i);
break;
}
}
// or
for (Report rep : report) {
if (rep.code.equals(searchTerm)) {
r = rep;
break;
}
}
// or
Report r = report.stream().filter(rep -> rep.code.equals(searchTerm)).findFirst().orElse(null);
现在,r
如果你找到了一些东西,它只是非空,所以,在循环之后:
if (r != null) {
// Print stuff.
} else {
// Print message saying you didn't find it.
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句