为什么我得到无效的类型

时间:2015-03-19 23:34:04

标签: java printing

当我试图打印方法时,我在第二行说错了 这里不允许使用void类型

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

 public static void printMenu(){

 System.out.println("***** Welcome to KAU Flight Reservation System *****"+
        "\n 1. Add Flight Details in the System"+
        "\n 2. Add Passenger Details in the System"+
        "\n 3. Make a new Booking"+
        "\n 4. Search and Print a Booking"+
        "\n 5. List Flight Status"+
        "\n 6. Exit from the System ");

}

3 个答案:

答案 0 :(得分:1)

您正试图在printMenu()内调用期望String值的System.out.println()方法。但是,printMenu()方法返回void。

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

public static String printMenu() {
    return ("***** Welcome to KAU Flight Reservation System *****"+
            "\n 1. Add Flight Details in the System"+
            "\n 2. Add Passenger Details in the System"+
            "\n 3. Make a new Booking"+
            "\n 4. Search and Print a Booking"+
            "\n 5. List Flight Status"+
            "\n 6. Exit from the System ");
}

有关返回类型的更多信息,请查看此Oracle Java教程:http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html 我还建议您阅读其中的一些教程,他们非常擅长教授一些基础知识。

答案 1 :(得分:0)

java中有两种函数。他们不返回任何值的程序和返回值的函数。当您在方法声明中添加单词void时,这意味着这是一个Procedures方法,它不会返回任何值,但System.out.print()方法需要Object种类的参数。

你的printMenu()方法应该是这样的。

 public static String printMenu(){

 String menu = "***** Welcome to KAU Flight Reservation System *****"+
        "\n 1. Add Flight Details in the System"+
        "\n 2. Add Passenger Details in the System"+
        "\n 3. Make a new Booking"+
        "\n 4. Search and Print a Booking"+
        "\n 5. List Flight Status"+
        "\n 6. Exit from the System ";
return menu;

}

答案 2 :(得分:0)

public class PrintMenu {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        printMenu();
    }

    public static void printMenu(){

         System.out.println("***** Welcome to KAU Flight Reservation System *****"+
                "\n 1. Add Flight Details in the System"+
                "\n 2. Add Passenger Details in the System"+
                "\n 3. Make a new Booking"+
                "\n 4. Search and Print a Booking"+
                "\n 5. List Flight Status"+
                "\n 6. Exit from the System ");

        }

}

您已经使用printMenu函数打印了菜单,因此您不应该在system.out.print函数内调用它。