在测试我的应用程序时,我遇到了一个与处理无效产品代码相关的小问题。我有一个
println
方法,旨在在用户输入无效的产品代码时通知用户。下面的代码片段说明了我的方法:
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)) {
// Code to display product details...
} else {
// System.out.println("The product cannot be located. Invalid Product");
}
}
// Code to prompt user for menu launch or exit...
}
如果
else
与 for
中的任何项目都不匹配,则当 searchTerm
循环内的 ArrayList
语句执行多次时,就会出现问题。这会导致多次打印无效的产品消息,这不是所需的行为。
我正在寻求有关如何更有效地处理这种情况的指导,以确保无效的产品消息仅显示一次,无论循环中的迭代次数如何。
任何建议或见解将不胜感激。谢谢!
将打印与循环分开:
循环浏览列表,直到找到该项目:
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.
}
使用布尔标志来检测是否找到产品:
boolean found = false;
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("****************************************************************************");
found= true;
}
}
//end of the loop
if(!found) System.out.println("The product cannot be located. Invalid Product");
将用于搜索“报告”中的项目的数据结构从 List 切换为 HashMap,以避免必须循环遍历所有项目:
HashMap<String, Integer> quickSearchMapping;
quickSearchMapping = new HashMap<>();
for(int i=0 ; i<report.size ; i++ ){
quickSearchMapping.put(report.get(i).code, i);
}
while(TRUE){
System.out.print("Please enter product code to search: ");
String searchTerm = in.nextLine().toUpperCase();
if quickSearchMapping.containsKey(searchTerm){
Report the_report = report.get(quickSearchMapping.get(searchTerm));
//print to user stuff in the_report
break; //break if you wish to
} else {
System.out.println("Code entered didn't match any product.");
}
}