修复 Java 中 Void Type Not Allowed Here 错误

我们在 Java 中创建大程序时会用到很多函数,有时可能会出现错误。编译器可能抛出的错误之一是本文中讨论的 void type not allowed here 错误。

什么是 void type not allowed here 错误

我们在 Java 中通过编写访问修饰符、返回类型、带括号的函数名来创建函数,并且函数体用花括号括起来。我们可以从一个函数返回多种类型的数据,但是当我们不想返回任何数据时,我们使用关键字 void 告诉编译器我们不想从该方法返回任何数据。

在下面的程序中,我们有一个类 JavaExample,它包含两个方法,第一个是 main() 函数,第二个是 printMessage1(),它有一个打印语句 System.out.println() 打印 printMessage1() 作为参数接收的消息。

printMessage1() 函数不返回任何内容,只打印一条消息;我们使用 void 类型作为返回类型。我们在 main() 方法中使用另一个 print 语句,并以 String 1 作为参数调用其中的 printMessage1() 函数。

当我们运行代码时,输​​出会抛出一个错误,void type not allowed here。这是因为 printMessage1() 已经有一个打印 value 的 print 语句,并且当我们在 print 语句中调用该函数时它不会返回任何内容; main 方法中没有可打印的内容。

public class JavaExample {
    public static void main(String[] args) {
        System.out.println(printMessage1("String 1"));
    }
    static void printMessage1(String value) {
        System.out.println(value);
    }
}

输出:

java: 'void' type not allowed here

修复 Java 中 void type not allowed here 错误 – 不要在 main() 方法中打印

这个错误的第一个解决方案是我们不在打印语句中调用函数 printMessage1(),因为方法本身已经有一个 System.out.println() 语句,并且它不返回任何内容。

在这段代码中,我们将 printMessage1() 函数的主体编写为 println() 语句。我们使用字符串作为参数调用 main() 中的 printMessage1() 方法。

public class JavaExample {
    public static void main(String[] args) {
       printMessage1("String 1");
    }
    static void printMessage1(String value) {
        System.out.println(value);
    }
}

输出:

String 1

修复 Java 中 void type not allowed here 错误 – 返回字符串而不是在 printMessage1() 中打印

第二种解决方案是在函数中指定返回类型,返回一个值,并在我们调用函数的任何地方打印它。

我们编写方法 printMessage1(),但返回类型 String。在方法的主体中,我们使用 return 关键字和我们想要在调用时返回的 value。在 main() 方法中,我们将函数 printMessage1() 调用到 print 语句中,但该方法返回值时不会出错。

public class JavaExample {
    public static void main(String[] args) {
        System.out.println(printMessage1("How are you doing today?"));
        System.out.println(printMessage1("String 2"));
    }
    static String printMessage1(String value) {
        return value;
    }
}

输出:

How are you doing today?
String 2