程序将要求用户输入他想要搜索的项目的代码。如果该项目的代码存在,它将打印到屏幕上,所有工作正常,直到这里。问题是当用户输入不存在的代码时,程序将无法运行。它不会打印“找不到项目”
这是代码
public void searchItem(){
boolean invalidInput;
int q = -1;
do {
try {
boolean found = false;
invalidInput = false;
System.out.println("Enter the item's code you want to search for : ");
q = s.nextInt();
out: for (int i = 0; i<items.length; i++){
if(q == items[i].getCode()){
System.out.println(items[i].toString());
found = true;
System.exit(2);
}
counter++;
}
if(!found)
System.out.print("Item not found");
} catch (InputMismatchException e) {
System.out.println("Please enter a valid code [Numbers Only]");
s.next();
invalidInput = true; // This is what will get the program to loop back
}
} while (invalidInput);
}
答案 0 :(得分:1)
如果我使用你的代码的这个(浓缩形式)它可以工作,并打印&#34;项目未找到&#34;正如我们所期望的那样......问题就在于我感觉到的其他地方......
如果您输入缺失(但有效)的商品编号,请提供进一步的信息!
public static void main(String[] args) {
boolean invalidInput;
int q = -1;
int[] items = { 1, 2, 3, 4 };
do {
boolean found = false;
invalidInput = false;
System.out.println("Enter the item's code you want to search for : ");
q = 5;
for (int i = 0; i < items.length; i++) {
if (q == items[i]) {
System.out.println(items[i]);
found = true;
System.exit(2);
}
}
if (!found)
System.out.print("Item not found");
} while (invalidInput);
}