0

For some reason when I run the file the answer seems to be 0. I'm still fairly new to Java so could someone explain to me what I've done wrong.. It all seems fine to 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;
 }
}

3 Answers3

0

In both of your instantiated bus objects, milesTravelled is less than mpg.

When you divide an int by an int, you get an int.

this.mpg/this.milesTravelled;

This will return 0 because the digits after the decimal point don't matter if it's an int.

To make them not ints, you could do things like:

this.mpg * 1.0 / this.milesTravelled

or

this.mpg/((double) this.milesTravelled)
Will Newton
  • 1,583
  • 13
  • 10
0

Use double instead of int or just carefully convert your int into a double before doing any division. This is a common problem for Java novices. Take a look at this and this. Try this out:

private double mpg;
private double milesTravelled;
private double used;

public bus(double mpg, double milesTravelled){
     this.mpg = mpg;
     this.milesTravelled = milesTravelled;
}

NOTE 1: When you do the division, make sure you check to see if milesTravelled is equal to 0 or not. If it is, then you will get an Exception.

NOTE 2: Change bus to Bus in the header definition of bus (which then means you will use Bus instead of bus). Using the capital letter in the beginning of a custom Object's name is a relatively common standard.

Community
  • 1
  • 1
0

As mentioned, diving ints gives an integer number. You can change type types of mpg and milesTravelled to double. Also you should be inverting the answer. m/g divided by m = m/mg = 1/g, not g. For example, at 10mpg traving 20m would use 2 gallons, but your calculation would give 1/2 gallon.

Always Learning
  • 5,510
  • 2
  • 17
  • 34