2014-10-16 168 views
0

我正在嘗試獲取特定人員前面的患者人數。我如何從for循環返回int?它始終返回0。從for循環返回int

public int pAhead(String name) { 
     Patient p; 
     int patientsAhead = 0; 
     for(int i= 0; i < list.size(); i++) 
     { 
      p = list.get(i); //get each object from array 
      String n = p.getName(); 
      if(name.equalsIgnoreCase(n)) 
      { 
       //if name passed is equal to object getName, than get the index of that object 
       patientsAhead = list.indexOf(p); 
      } 
     } 
     return patientsAhead; 
    } 
+2

你確定0是錯誤的結果嗎? – wvdz 2014-10-16 11:21:57

+1

你在哪裏聲明瞭'list'?因爲它沒有被傳遞到代碼中的函數u posted – 4rlekin 2014-10-16 11:22:03

+0

將if語句的真實部分更改爲'return i;'。 – munyul 2014-10-16 11:22:21

回答

2

首先你不需要list.indexOf(p);,因爲你已經擁有了循環變量i

返回它只是做

if(name.equalsIgnoreCase(n)) { 
    return i; 
} 

注意indexOf可能導致別的東西取決於你是如何實現的equals,你正在比較人的名字。

所有的說法,請確保您的列表實際上包含一些元素。

0

如果我明白你的問題,你所要做的就是當你看到你感興趣的號碼時添加一個break語句。

所以:

public int pAhead(String name) { 
     Patient p; 
     int patientsAhead = 0; 
     for(int i= 0; i < list.size(); i++) 
     { 
      p = list.get(i); //get each object from array 
      String n = p.getName(); 
      if(name.equalsIgnoreCase(n)) 
      { 
       //if name passed is equal to object getName, than increase your counter 
       patientsAhead = i; 
       break; 
      } 
     } 
     return list.size() - patientsAhead; 
    } 
1

嘗試返回i的值。它會給你與傳入名稱匹配的值。

public int pAhead(String name) { 

    Patient p; 
    int patientsAhead = 0; 
    for(int i= 0; i < list.size(); i++) 
    { 
     p = list.get(i); //get each object from array 
     String n = p.getName(); 
     if(name.equalsIgnoreCase(n)) 
     { 
      //if name passed is equal to object getName, than increase your counter 
      patientsAhead = i; 
     } 
    } 
    return patientsAhead; 
} 
0

這個答案假定list變量是包含前面病人的病人和你想要的號碼,患者名單,是你要找的病人的指數。

如果你有Patient對象,你想查找,只是做pAhead = list.indexOf(patient)應該給你相同的結果,而不使用for循環。只要確保您檢查結果是否定的,那麼這意味着您要查找的患者不在列表中。

此解決方案取決於定義了Person.equal()方法。一些IDE可以爲你生成它。

如果您要麼沒有對象,或者你不能(或不願)改變equal()方法,可以循環就像您和return i內循環,像其他答案建議:

for (int i=0; i<=list.size(); i++) { 
    if (name.equalsIgnoreCase(list.get(i).getName())) { 
     return i; 
    } 
}