2017-11-10 55 views
1

在Java中的初學者,我尋找的方式來返回與我的函數「readPeople()」與我的ArrayList「this.list」關聯的名稱由於用戶給出的ID。 這裏是我的代碼:如何用java中的元素返回名稱?

public class PersonneC implements PersonneDB { 
    this.list = new ArrayList(); 

    People marie = new People(1, "Bower", "Marie"); 
    list.add(marie.toString()); 

     public PeopleWithId readPeople(int idPeople) { 
     PeopleWithId peoplename = null; 
     for(int i = 0; i < list.size(); i++) { 
      if(liste.get(i).equals(idPeople)) { 
       result = list.get(i); 
      } 
     } 
     return result.getPeopleName(); //ERROR INCOMPATIBLE TYPES 
     } 

通緝的結果返回:鮑爾

+0

我們可以讓人們類和什麼類型的結果,我認爲是人民和檢查list.add(marie.toString( )) – crammeur

+2

'getPeopleName()'可能返回一個'String',但是你的方法聲明'PeopleWithId'爲返回類型。它不兼容。將它改爲'public String readPeople(int idPeople)' – davidxxx

+0

,除了編譯器錯誤外,用'return list.get(i);'替換'result = list.get(i);'會更有效率'for'循環返回'null',或者甚至更好地使用'Optional '。 –

回答

1
ArrayList<People> list = new ArrayList<>(); 

// add people to the list 
People marie = new People(1, "Bower", "Marie"); 
list.add(marie); 

// Search function 
    public String readPeople(int idPeople) { 
    People p = null; 
    for(int i = 0; i < list.size(); i++) { 
     // If equal than it is the result 
     if(list.get(i).id == idPeople) { 
      p = list.get(i); 
      break; 
     } 
    } 
    return p == null ? null : p.getName(); 
    } 
+0

謝謝你的回覆。 但是,我被告知行「if(list.get(i).id == idPeople){」在索引「id」下面的錯誤「無法解析符號ID」,爲什麼? – Paul

+0

也許你的身份證是私密的或者是受保護的,或者你把你的身份命名爲別的。 –

+0

你可以看到我將People對象添加到數組而不是String。 –

0

你得到不兼容類型的原因是因爲在你的函數readPeople你告訴它返回PeopleWithId,在那裏你正在返回一個字符串。

在public修飾符更改PeopleWithId之後,因爲此對象不存在,請將其更改爲String。它所做的是告訴你想要從中獲得的對象的類型的函數,在這種情況下是一個String,因爲你的名字已經被存儲爲一個字符串。

0

你的方法返回一個string,並且readPeople的返回類型爲PeopleWithId

相關問題