开发者

Error "Void type not allowed here." Please help me

开发者 https://www.devze.com 2023-01-23 01:56 出处:网络
It keeps giving me an error in \"Void type not allowed here.\" public class BugTester { public static void main(String[] args) {

It keeps giving me an error in "Void type not allowed here."

public class BugTester {
    public static void main(String[] args) {
        Bug bugsy =  new Bug(10); 
        bugsy.move();  //now the position is 11
        bugsy.turn();      
        bugsy.move();  //now the position is 10
        bugsy.move();
        bugsy.move();
        bugsy.move();

        // Error message highlights this.
        System.out.println("The bug position is a开发者_如何学编程t "+bugsy.move());
    }
}


The move() method of Bug does not return a value. It is a void method. You cannot concatenate nothing to a String.

Maybe there is another method of Bug that you want to print the value of like getPosition()?


Looks like you have:

class Bug {
    public void move() {
       // ...
    }
}

If you want to println bugsy.move(), then have move() return the position, not void.


A common way is to override toString() method which contains major information of a Bug object, including position.

class Bug{

  @Override
  public String toString(){
    return "position="+position;//If you have other attributes to show, modify the mothod rather than modifying its invoker
  }

}

Then call System.out.println("The bug is "+bugsy);

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号