-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