2014-10-16 119 views
-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); 
} 
+1

請正確格式化您的代碼。你會更容易看到這樣的錯誤。 – vikingsteve 2014-10-16 12:02:23

+0

因爲您在找到某些內容後退出程序,您可以在循環後簡單地打印出來。 – Seega 2014-10-16 12:09:04

+0

爲什麼你不使用'break'就像你在其他[question]中提出的一樣(http://stackoverflow.com/questions/26398247/the-for-loop-doesnt-work-as-what-it -supposed-to)? – yunandtidus 2014-10-16 12:10:14

回答

1

如果我你的代碼的使用(濃縮型)它的工作原理,並打印「沒有找到」正如我們期望...所以問題是我覺得的其他地方....

請提供進一步的信息,如果你輸入一個缺失(但有效)的項目編號!

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); 
}