2013-03-04 47 views
-1

請幫我修復錯誤。public boolean removeStudent(int id)

public boolean removeStudent(int id) 
{ 
    for (Student student : this) 
    { 
     if ((student.getID()) == (id)) 
     return true; 
     id.remove(); 
    } 
    return false; 
} 

錯誤:int無法解除引用。 我試圖從基於id的列表中刪除學生。但是.remove與整數不相容。

回答

0

難道你不打算撥打student.remove()或其他方面的內容嗎?

此外,該代碼將不會被之前的return true行命中。

+4

或者'this.remove(student)'?或者是其他東西?沒有足夠的上下文。 – 2013-03-04 01:48:59

+0

@JeremyRoman touche。 – 2013-03-04 01:49:45

+0

雅工作非常感謝。 – user2130183 2013-03-04 01:54:31

0

此代碼看起來不太好。首先:移除調用是錯誤的,移除總是被調用,因爲你的if語句沒有用括號封裝。

1

id是一個原始類型int,所以它沒有任何方法。

id.remove(); //will never compile 

更改您的代碼

for (int x =0; x < this.size();x++) { 
    //your if should contain the removal and the return statements 
    if ((this.get(x).getID()) == (id)) { 
     this.remove(this.get(x)); 
     return true; 
    } 
} 
return false; 
0

重新縮進你的代碼,你會看到這個問題:

public boolean removeStudent(int id) 
{ 
    for (Student student : this) 
    { 
     if ((student.getID()) == (id)) { 
      return true; 
     } 
     id.remove(); 
    } 
    return false; 
} 

見你當前正在做的事情:一旦你打學生相匹配的ID ,你會立即跳出該方法,返回true。在此之前,您將移除您所重複的所有學生。即你正在移除所有學生,直到找到一個匹配的。

這對我來說看起來不太正常。

我敢打賭,你想要做的是:刪除所有具有匹配ID的學生。如果任何學生被刪除,則返回true,否則返回false。

如果是的話,試着去了解這段代碼:(我不是給你直接的答案。如果你能理解這是怎麼回事就在這片代碼,那麼你可以很容易地解決你的)

// print out only odd numbers in the list, and return true if there is any. 
boolean printOdd(List<Integer> numbers) { 
    boolean oddFound = false; 
    for (int i : numbers) { 
    if ((i % 2) != 0) { 
     System.out.println("Odd Number Found: " + i); 
     oddFound = true; 
    } 
    } 
    return oddFound; 
} 

在你的代碼更多的問題:

你不使用似乎對-每個看起來正常。你的班級是一個集合嗎?

for (Type a : b) {...} 

expect b是一個Collection(更確切地說是Iterable)還是一個數組。

另一個問題是,id是一個整數,你期望id.remove()會做什麼?你正在告訴Integer做「刪除()」

我假設你正在做類似this.studentList.remove(id)this.studentList.remove(student)

相關問題