2017-08-14 161 views
-3

有人可以请回答为什么这段代码给出错误吗?为什么void方法无法在system.out.println中调用

package hello; 

public class Hello { 

    public void eat() { 
     System.out.println("eating"); 
    } 

    private String run() { 
    return "dwedsdfsdfsdf fsdf rgdsfG"; 

    } 

    public static void main(String[] args) { 
     //System.out.println("Hello bhopi"); 
     //Hello hello = new Hello(); 
     Hello mahir = new Hello(); 
     //String y = mahir.eat(); 

     System.out.println(mahir.run()); 
     System.out.println(mahir.eat()); 
    } 
} 
+0

void方法返回什么? – LazerBanana

+1

标记 - 关闭主题 - '为什么我的代码不起作用?是一个寻求调试支持的问题,不应该回答/询问。 – LazerBanana

回答

1

因为void方法不返回任何东西,所以没有什么可打印的。方法System.out.print()需要一个对象作为参数来打印。

1

1)没有方法可以接受作为参数调用void方法。
这就好比你将一个void参数传递给一个方法。

2)这里println()PrintStream.println()方法作为out字段声明为PrintStream
要在调用它时正确编译,必须指定一个与此方法的重载版本之一相匹配的参数。

相关问题