2012-12-10 78 views
-1

的語句im在lName數組中搜索姓氏,一旦在數組中找不到姓氏else輸出顯示每次未找到循環的循環,我將如何去解決這個問題?如果我在else部分中添加一個返回false語句,它會在檢查數組的第一個位置後停止循環。搜索方法,如果在以下代碼中顯示多次

任何幫助將appriciated!

public boolean search(String StudentlName) 
{ 
    boolean found = true; // set flag to true to begin first pass 

    while (found ==true) 
    { 
     for (int index = 0; index<lName.length; index ++) 
     { 
      if (StudentlName.equalsIgnoreCase(lName[index]) ) 
      { 
       System.out.println(course+"\n"+ 
       "Student ID = \t"+index+"\n"+ 
       unitTitle + "\n" + 
       fName[index] + "\n" + 
       lName[index] + "\n" + 
       Marks[index] + "\n" + "\n"); 
       found = false; 

       return true;//Stops The Loop once Found used to stop infinite loop 
      } 
      else 
      { 
       System.out.println("Student Not Found"); 
      } 
     } 
     return false; 
    } 
    return true; 
} 

如果沒有找到這個示出輸出

學生未找到

學生未找到

學生未找到

學生未找到

學生的結果未找到

+0

未來,您應該在發佈之前正確設置代碼的格式,以便人們閱讀時更容易。 –

回答

4

在循環之外打印「找不到學生」,就在您返回false之前。你只返回一次錯誤,到那時你才知道你找不到這個學生;不需要「其他」。

+0

賓果得到它謝謝! – Bunion

0
public boolean search(String StudentlName) 
{ 
    boolean found = true; // set flag to true to begin first pass 

    while (found ==true) 
    { 
    for (int index = 0; index<lName.length; index ++) 
    { 
     if (StudentlName.equalsIgnoreCase(lName[index]) ) 
     { 
      System.out.println(course+"\n"+ 
      "Student ID = \t"+index+"\n"+ 
      unitTitle + "\n" + 
      fName[index] + "\n" + 
      lName[index] + "\n" + 
      Marks[index] + "\n" + "\n"); 
      found = false; 

      return true;//Stops The Loop once Found used to stop infinite loop 
     } 


    } 
    System.out.println("Student Not Found"); 
    return false; 
    } 
return true; 
} 

這會爲你工作,因爲每次你想要搜索的姓氏都會執行部分。

0

爲了簡化,我很確定while循環沒有什麼好處。它會一直返回它的第一次迭代,所以它是不必要的。所以刪除發現和while循環,我們留下了。

public boolean search(String StudentlName) 
{ 
    for (int index = 0; index<lName.length; index ++) 
    { 
     if (StudentlName.equalsIgnoreCase(lName[index]) ) 
     { 
      System.out.println(course+"\n"+ 
       "Student ID = \t"+index+"\n"+ 
       unitTitle + "\n" + 
       fName[index] + "\n" + 
       lName[index] + "\n" + 
       Marks[index] + "\n" + "\n"); 
      return true;//Stops The Loop once Found 
     } 
     //Don't do anything when they aren't equal, except test the next one 
    } 
    //We checked everything, found nothing, So now print the message. 
    System.out.println("Student Not Found"); 
    return false; 
}