我在这里摸不着头脑......
问题: 我正在做一个基本方法来计算两个对象字段并返回一个值。由于某种原因它返回一个空值。我知道我忽略了一些非常简单的事情,但它让我很烦恼。
代码:
public class Tools {
// Instance variables
private String type;
private int age;
private int eol;
private Double lifeLeft;
// Constructor
public Tools(String type, int age, int eol) {
this.type = type;
this.age = age;
this.eol = eol;
}
public String toString() {
return type + " has reached " + lifeLeft() + "% of its life expectancy.";
}
public Double lifeLeft() {
lifeLeft = (double)((this.age / this.eol) * 100);
return lifeLeft;
}
}
我只是试图计算 lifeLeft =age/eol * 100 以获得百分比。我已将问题追溯到我的 lifeLeft() 方法。由于某种原因,它没有获取对象的年龄和生命周期。我做了一些 System.out.println(age, eol) 等来测试,变量值反射(reflect)为 0。
旁注: 我从子类对象调用 super.toString() 但我认为这在这里并不重要。
子类以供引用,以防万一。
public class Wrench extends Tools {
// Instance variables
private Double capacity;
// Constructor
public Wrench(String type, int age, int eol, Double capacity) {
super(type, age, eol);
this.capacity = capacity;
}
public String toString() {
return "Your " + capacity + "\" " + super.toString();
}
}
最佳答案
(this.age/this.eol)
为零,因为整数除法向下舍入。
关于java - 类方法返回0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37470425/