-1
程序将要求用户输入他想要搜索的项目的代码。如果该项目的代码存在,它会将其打印到屏幕上,并且一切正常,直到这里。问题是当用户输入不存在的代码时,该程序将无法工作。它不打印“没有找到”if(!found)语句无法正常工作
这里是代码
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);
}
请正确格式化您的代码。你会更容易看到这样的错误。 – vikingsteve 2014-10-16 12:02:23
因为您在找到某些内容后退出程序,您可以在循环后简单地打印出来。 – Seega 2014-10-16 12:09:04
为什么你不使用'break'就像你在其他[question]中提出的一样(http://stackoverflow.com/questions/26398247/the-for-loop-doesnt-work-as-what-it -supposed-to)? – yunandtidus 2014-10-16 12:10:14