Error: 'void' type not allowed here

戏子无情 提交于 2019-12-02 07:19:55

问题


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);
  }
}

回答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;
}



回答2:


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

public int mileage() {
    return miles;
}


来源:https://stackoverflow.com/questions/27049947/error-void-type-not-allowed-here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!