2014-10-16 117 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); 
}