【问题标题】:My Java Code keeps returning wrong values?我的 Java 代码不断返回错误的值?
【发布时间】:2018-05-09 19:06:39
【问题描述】:
public class CirclePlus implements Relatable {
    public double radius = 0;
    final double PI = 3.14159;

CirclePlus(){}

public CirclePlus(double radius) {
    radius = radius;
}

public double getArea() {
    return PI * (radius * radius);
}

public double isLargerThan(Relatable other) {
    CirclePlus otherCirc = (CirclePlus)other;
    if (this.getArea() < otherCirc.getArea())
        return -1;           
    else if (this.getArea() > otherCirc.getArea())
        return 1;            
    else
        return 0;

}

/// 下面的主类

    public static void main(String[] args) {
    CirclePlus c1 = new CirclePlus(50);
    CirclePlus c2 = new CirclePlus(0);

    if(c1.isLargerThan(c2) == 1) {
      System.out.println("c1 is bigger!");
  }
  else
      System.out.println("c1 has the same size as that of c2 or smaller than"
              + " c2!");

}

输出总是:

"c1 has the same size as that of c2 or smaller than"

不管我把两个圆的半径改成什么。

这是我的代码,它在最后的 else 语句中一直返回 0,但即使在 if/else if 语句中满足条件,它也会忽略它们,只是走到底部并返回 0;

你能帮我解决这个问题吗?另外,为了让我了解更多,你能解释一下java为什么这样做吗?

只是帮助也可以,非常感谢!

【问题讨论】:

  • 这段代码是什么???IsLargerThan应该返回一个布尔值.....jdk已经有一些方法
  • @ΦXocę웃Пepeúpaツ 没错,方法签名更像是 Comparator 的实现。
  • 大家好,我对其进行了修改并添加了更多信息。我很抱歉我是新来的,所以我几乎没有添加任何信息是我的错。我希望这些信息有所帮助,您可以帮助我清楚地理解问题。非常感谢!

标签: java if-statement netbeans return


【解决方案1】:

错误出现在以下一段代码中:

[...]
public double radius = 0;
[...]
public CirclePlus(double radius) {
    radius = radius;
}

这里,Java 尝试将本地方法变量radius 分配给自己,这对您的类成员变量radius 没有影响。

为避免此问题,您必须像这样限定作业的左侧

public CirclePlus(double radius) {
    this.radius = radius;
}

或者像这样为局部变量使用不同的名称

public CirclePlus(double r) {
    radius = r;
}

这样Java可以区分本地方法变量和类变量。

其他一些小问题:你的类变量 radius 应该是私有的而不是公共的,你的 isLargerThan 方法应该返回一个 int 而不是 double。

另外,如果一个名为isLargerThan 的方法返回一个布尔值会更合乎逻辑。你也可以实现Comparable 接口:

int compareTo(CirclePlus other) {
    return Double.compare(this.getArea(), other.getArea());
} 

【讨论】:

  • 非常感谢@Modus Tollens 非常有帮助,我非常感谢你写得这么好!
猜你喜欢
  • 2021-08-27
  • 2018-07-21
  • 2011-12-04
  • 2021-07-17
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多