java - 类方法返回0

标签 java

我在这里摸不着头脑......

问题: 我正在做一个基本方法来计算两个对象字段并返回一个值。由于某种原因它返回一个空值。我知道我忽略了一些非常简单的事情,但它让我很烦恼。

代码:

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/

相关文章:

java - 将 Integer 的 ArrayList 与多个 ArrayList 进行比较以提取共同值

java - 无法从下拉菜单中选择选项

java - 如何在 StdOut.printf (JAVA) 中使用整数 n

java - 在 Packages exec 期间不允许进行 DML 操作

java - 来自包含字符像素宽度的 HashMap 的像素完美自动换行

Java:无法调用另一个类

java - 在 Java 中覆盖系统属性(无代码)

java - 试图理解 subscribeActual()

java - 应用程序中不同模块的多连接池配置

java - Matcher.Find() 在应该为 true 时返回 false