I am scratching my head here...
Problem: I am doing a basic method to calculate two object fields and return a value. For some reason it is returning a null value. I know I am overlooking something incredibly simple but it is kicking my butt.
Code:
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;
}
}
I am simply attempting to calculate lifeLeft = age/eol * 100 to get a percentage. I have tracked the issue back to my lifeLeft() method. For some reason it is not getting the age and eol of the object. I have done some System.out.println(age, eol) etc to test and the variable values reflect 0.
Sidenote: I am calling super.toString() from a subclass object but I don't think that matters here.
Subclass for reference in case it does.
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)
is zero because integer division rounds down.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments