public boolean removeStudent(int id)

时间:2013-03-04 01:47:15

标签: java

请帮我修复错误。

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

错误:int无法解除引用。 我正在尝试从基于id的列表中删除学生。但是.remove与int不兼容。

4 个答案:

答案 0 :(得分:1)

idint,是一种原始类型,因此它没有任何方法。

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;

答案 1 :(得分:0)

你不是要打电话给student.remove()或其他什么东西吗?

此外,该代码不会被其前面的return true行点击。

答案 2 :(得分:0)

此代码看起来不太好。首先:删除调用是错误的,并且总是调用remove,因为你的if语句没有用括号括起来。

答案 3 :(得分: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) {...}

期望b成为集合(更准确地说,是Iterable)或数组。

另一个问题是,id是一个整数,你期望id.remove()会做什么?你告诉整数做“删除()”

我假设您正在执行this.studentList.remove(id)this.studentList.remove(student)

之类的操作