方法声明无效;需要返回类型?

时间:2015-04-22 00:42:17

标签: java

我收到了无效的方法声明;本节要求的返回类型:

public updateFrequency(int frequence) {
    frequence = frequency++;
    return frequence;
}

以下完整代码

public class Node {
String number; //node data
Node left;  //points to the left sub-tree
Node right; //points to the right sub-tree
int frequency;

public Node(String s) {
    number = s;
    left = null;  //set value to null because it is empty
    right = null; //set value to null because it is empty
    frequency = 1; //starting frequency value
}

public void add(String value) {
    if (left == null) {
        left = new Node(value);
    }
    else if (right == null) {
        right = new Node(value);
    }
    else {
        if (countChildNodes(left) <= countChildNodes(right)) {
            left.add(value);
        }
        else {
            right.add(value);
        }
    }
}

public int countChildNodes(Node node) {
    int count = 0;
    if(node != null) {
        count = 1 + countChildNodes(node.getLeft()) + countChildNodes(node.getRight());
    }
    return count;
}

public updateFrequency(int frequence) {
    frequence = frequency++;
    return frequence;
}

public void increaseFrequency() {  //increases the frequency of string occurences
    frequency++;
}

public int getFrequency() { //returns frequency of given string
    return frequency;
} 

public Node getRight() {
    return right;
}

public Node getLeft() {
    return left;
}

public String getNumber() {
    return number;
}

}

有人能指出我的错误吗?我的其他课程名为TreeDemo和BinarySearchTree,但我不确定这是否重要。

感谢您的帮助。

6 个答案:

答案 0 :(得分:1)

您没有在方法中指定的返回类型。如果要返回String,则可以在声明中说出String。您几乎可以退回任何类型。

您的代码将如下所示:

public int updateFrequency(int frequence)
{
   frequence = frequency++;
   return frequence;
}

希望这会有所帮助:)

答案 1 :(得分:0)

您需要声明方法的返回类型。

public int updateFrequency(int frequence) {
    frequence = frequency++;
    return frequence;
}

我希望有所帮助!

答案 2 :(得分:0)

如错误所示:&#34;需要返回类型&#34;。您的方法需要返回类型。 public int updateFrequency(int frequency){

答案 3 :(得分:0)

updateFrequency没有返回类型。您可以将其指定为:

public int updateFrequency(int frequence) {
    frequence = frequency++;
    return frequence;
}

答案 4 :(得分:0)

对于任何不是构造函数的实例方法,您必须声明一个返回类型。在您的情况下,由于您返回的是int,因此您的方法应该看起来像public int updateFrequency(int frequence) {

顺便说一句,在您的实现中,frequence变量可以是updateFrequency()方法的本地变量。您不需要将其作为参数传递

答案 5 :(得分:0)

目前您还没有指定返回类型。因此,如果您尝试返回方法的frequency值,那么您可以:

public int updateFrequency(int frequence) {
    this.frequence = frequency++;
    return this.frequence;
}

如果您不想返回值,则仍需要添加void返回类型并执行此操作:

public void updateFrequency(int frequence) {
    this.frequence = frequency++;
}

此外,由于frequency是一个实例变量,您可以这样做:

public void updateFrequency() {
    this.frequency++;
}