2017-02-06 46 views
0

好吧,所以我有下面的代碼,不管它返回給我一個-1。我想擁有它,這樣如果id匹配,那麼它將返回並返回索引,但如果它在遍歷整個數據集後不匹配,它將返回一個負值。我要去哪裏錯在這裏:Java返回的困境

public class StudentCollection { 

private String[] ids = new String[] {"Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty"}; // keeps identification numbers of students 
private String [] names = new String[] {"Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty"};; // keeps the names of students 
private int size = 0; // number of students currently in the collection 


private int findIndex(String id) { 
    int noIndex = 1; 
    for (int i=0;i<ids.length;i++){ 
     if((ids[i].equalsIgnoreCase(id))){ 
      System.out.println("The index of this student is " +i); 
      } 

     else { 
      noIndex = -1; 
      System.out.println(noIndex); 
      break;}  
    } 

    return noIndex; 
} 
+1

代碼中有什麼'ids'? –

+1

提示:您在哪裏將noIndex設置爲要返回的值?你什麼時候該休息?爲什麼你否定equalsIgnoreCase的結果? – samgak

回答

1

這裏是如果指數被發現,然後返回其編號,其中的解決方案,否則,如果它不檢查整個數組後,返回-1並打印適當的字符串。

private int findIndex(String id) { 
    int noIndex = -1; 
    for (int i = 0; i < ids.length; i++) { 
     if (ids[i].equalsIgnoreCase(id)) { 
      System.out.println("The index of this student is " + i); 
      return i; 
     } 
    } 
    System.out.println(noIndex); 
    return noIndex; 
} 

您還可以使用Java 8個流:

private int findIndex(String id) { 
    OptionalInt index = IntStream.rangeClosed(0, ids.length-1) 
           .filter(i -> ids[i].equalsIgnoreCase(id)) 
           .findFirst(); 
    if(index.isPresent()) { 
     int i = index.getAsInt(); 
     System.out.println("The index of this student is " + i); 
     return i; 
    } 
    System.out.println(-1); 
    return -1; 
} 
+0

謝謝你這個工作!我也明白爲什麼它也是 – Oluwatosin

0

我想你需要的東西是這樣的:

private int findIndex(String id) { 

    for (int i=0; i<ids.length; i++){ 

     if(ids[i].equalsIgnoreCase(id)){ 

      System.out.println("The index of this student is " +i); 

      return i; 
     } 
    } 

    return -1; 
} 
+0

第二種方法是區分大小寫的,因此不起作用。 –

+0

事實上,我認爲你是對的(y) –

+1

然後糾正它,否則一些downvoters會來(不是我;)。 –

1

現在你擁有了它,所以當ids[i].equalsIgnoreCase(id)是真的,這將設置noIndex -1(else語句),並打破了循環,這將使其返回-1。當這是錯誤的,它會打印出索引。 像其他人已發佈的一樣,這裏是查找索引的代碼。

private int findIndex(String id) { 
    for (int i=0;i<ids.length;i++){ 
     if(ids[i].equalsIgnoreCase(id)){ 
      return i; 
     } 
    } 

    return -1; 
} 
+0

OP在返回之前也會打印它們。 –