-1
public int removeAll(int i){
    while (head.getData() == i){
        int value = head.getData();
        head = head.getNext();
        return value;
    }
    Node curr = head;
    while (curr.getNext() != null){
        if (curr.getNext().getData() != i){
            int value = curr.getNext().getData();
            curr.setNext(curr.getNext().getNext());
            return value;
        }
        else {
            curr = curr.getNext();
        }

    }

}

它一直说没有为函数指定返回,因为它是嵌套的,而不是在外循环上。我怎么能把它拿出来清除这个?

4

4 回答 4

0

Change your code to:

public int removeAll(int i) {
    int value = 0; //You can check in caller code like if it is 0 (or put your own value like -1) then do something

    while (head.getData() == i) {
        value = head.getData();
        head = head.getNext();
    }

    Node curr = head;
    while (curr.getNext() != null) {

        if (curr.getNext().getData() != i){
            value = curr.getNext().getData();
            curr.setNext(curr.getNext().getNext());
        }
        else {
            curr = curr.getNext();   //In this part, there is no return code
        }

     }
     return value;
}

Since there was at-least one condition which can be satisfied, where there were no return statement, you were getting error. This code should work fine.

于 2013-02-21T04:08:52.057 回答
0

如果程序控制从未在您的removeAll方法的任何 while 循环中到达怎么办。在这种情况下,您应该返回一个整数值,但程序永远不会到达任何return语句。因为这个编译器给你错误。

return在函数末尾添加语句。

于 2013-02-21T04:13:12.053 回答
0

符合JLS 8.4.7,该程序编译失败,因为它确定该方法可以正常完成:

如果将方法声明为具有返回类型,则如果方法的主体可以正常完成,则会发生编译时错误。

在您的情况下,程序可能会在不进入任何 for 循环的情况下终止,因此不会返回任何内容。

于 2013-02-21T04:14:09.783 回答
0

我认为你需要这个:

Node curr = head;
int value = -1;  // change is here
while (curr.getNext() != null){
    if (curr.getNext().getData() != i){
        value = curr.getNext().getData();  // change is here
        curr.setNext(curr.getNext().getNext());
        break;  // change is here
    }
    else {
        curr = curr.getNext();
    }
}
return value;   // change is here
于 2013-02-21T04:05:34.880 回答