Error: 'void' type not allowed here

12,575

Solution 1

The error message is telling you exactly what is wrong -- you're trying to extract a result from a method that does not return a result.

Instead, have the mileage() method return a String, not print out a String.

public String mileage() {
    return String.valueOf(miles);
}

Myself, I'd make this a getter method, and instead would do:

public int getMiles() {
    return miles;
}

Solution 2

Car.mileage() is void, i.e., does not return anything. It needs to return something, like in:

public int mileage() {
    return miles;
}
Share:
12,575
Sam
Author by

Sam

Updated on June 04, 2022

Comments

  • Sam
    Sam almost 2 years

    I'm learning to use classes and part of my assignment is to make this Car class. I'm getting an error on line 6 where I attempt to print of the results of the methods within the class. I think this means that I'm attempting to print something that doesn't exist and I suspect it's the mileage method. I tried changing it to return miles, but that didn't work either. Any ideas?

    public class TestCar {
      public static final void main(String args[]) {
    
        Car c = new Car ();
        c.moveForward(4);
        System.out.println ("The car went" + c.mileage() + "miles."); // <-- L6
      }
    }
    
    class Car {
      public int miles = 2000;
      public void moveForward(int mf) {
        if (miles != 2000) {
            miles += mf;
        }
      }
    
      public void mileage() {
        System.out.print(miles);
      }
    }
    
  • jmj
    jmj over 9 years
    also lots of bugs with accessor methods, field hiding
  • nmore
    nmore over 9 years
    mileage is fine, but it can return an int. No need to convert to String.