class - Java - Costum Classes, code not working -
for reason when run file answer seems 0. i'm still new java explain me i've done wrong.. seems fine me.
public class bus { public static void main(string[] args) { bus fivepm = new bus(23, 120); bus elevenam = new bus(27, 140); system.out.println(fivepm.gallonsused()); system.out.println(elevenam.gallonsused()); } private int mpg; private int milestravelled; private double used; public bus(int mpg, int milestravelled){ this.mpg = mpg; this.milestravelled = milestravelled; } public double gallonsused(){ this.used = this.mpg/this.milestravelled; return this.used; } }
in both of instantiated bus objects, milestravelled less mpg.
when divide int int, int.
this.mpg/this.milestravelled;
this return 0 because digits after decimal point don't matter if it's int.
to make them not ints, things like:
this.mpg * 1.0 / this.milestravelled
or
this.mpg/((double) this.milestravelled)
Comments
Post a Comment