在核心Java中编译时间错误

时间:2014-12-05 07:00:02

标签: java

//当我调用hello方法时,为什么显示编译时错误?

public class Test {

  public static void main(String [] args) {

            System.out.println(hello());
   }

 public static void hello() {

          System.out.println("from hello");
  }
}

4 个答案:

答案 0 :(得分:2)

由于hello()未返回StringObjectPrintStream中定义的各种println方法所接受的任何其他类型。< / p>

实际上,你可以将任何类型的参数传递给println并获得某种形式的输出,但由于你的方法的返回类型被声明为void,你实际上并没有传递一个参数。

您可以通过将hello()方法更改为类似的方法来消除错误,例如:

public static String hello() {
    return "Hello world";
}

或者将方法调用更改为:

System.out.println();

答案 1 :(得分:1)

方法hello()不会返回任何内容。

尝试这样的事情:

public class Test 
{
  public static void main(String [] args) 
  {
      System.out.println(hello());
  }

  public static String hello() 
  {
      return "Hi!";
  }
}

答案 2 :(得分:0)

方法hello必须返回一个值。请参阅以下代码段:

public class Test {

    public static void main(String [] args) {
        System.out.println(hello()); //this method must return value
    }

    public static String hello() {
        return "Hello Baghi!";
    }
}

答案 3 :(得分:0)

这是因为你的hello方法没有返回任何值/对象(println()的任何可打印)。

您可以按如下方式更改方法:

public static void main(String[] args)
{
    System.out.println(hello());
}
public static String hello() 
{
    return ("from hello");
}

或者,更改调用方法的方式:

public static void main(String[] args)
{
    hello();
}
public static void hello() 
{
   System.out.println("from hello");
}