【问题标题】:Illegal start of expression (method) [closed]非法开始表达(方法)[关闭]
【发布时间】:2014-11-17 22:13:24
【问题描述】:

最近决定学习一点Java,但我在第一个障碍时被难住了。这是我非常基本的代码:

import java.util.Scanner;

class helloWorld{

public static void main(String[] args){
    Scanner user_input = new Scanner(System.in);

    int a = 50;
    String first_name;
    String last_name;

    public static int funcName(int a, int b) {
    }
}
}

据我所知,没有错误。但是,在编译时我收到此错误:

Dominics-MacBook-Pro:helloworld dominicsore$ javac helloworld.java
helloworld.java:12: error: illegal start of expression
public static int funcName(int a, int b) {
^
helloworld.java:12: error: illegal start of expression
public static int funcName(int a, int b) {
       ^
helloworld.java:12: error: ';' expected
public static int funcName(int a, int b) {
             ^
helloworld.java:12: error: '.class' expected
public static int funcName(int a, int b) {
                               ^
helloworld.java:12: error: ';' expected
public static int funcName(int a, int b) {
                                ^
helloworld.java:12: error: ';' expected
public static int funcName(int a, int b) {
                                       ^
6 errors

我已经搜索和搜索,所有常见的回复都是拼写错误和放错位置的括号,但据我所知,情况并非如此。

不确定它是否会有所不同,但我在 Mac 上,使用 vim 编辑器,我正在从终端编译。

感谢任何建议。

【问题讨论】:

  • Java 不支持嵌套方法。你在尝试什么?
  • 这个问题似乎离题了,因为它是关于基本语法特性的,将来不会帮助任何人。语法问题本质上是 Stack Overflow 上的题外话。

标签: java methods expression


【解决方案1】:

funcName 是在 main 方法中定义的,它必须在它之外:

import java.util.Scanner;

class helloWorld{

    public static void main(String[] args){
        Scanner user_input = new Scanner(System.in);

        int a = 50;
        String first_name;
        String last_name;
    }
    public static int funcName(int a, int b) {

    }
}

【讨论】:

    【解决方案2】:

    你不能在另一个方法中声明一个方法。将funcName 移出main 方法:

    import java.util.Scanner;
    
    class helloWorld{
    
        public static void main(String[] args){
            Scanner user_input = new Scanner(System.in);
            int a = 50;
            String first_name;
            String last_name;
            //do something more here, probably to call
            //to your funcName method
        }
    
        public static int funcName(int a, int b) {
            //method implementation
            //since it doesn't return anything (yet), I add this line
            //just for compilation purposes
            return 0;
        }
    }
    

    【讨论】:

    • 而且有返回类型的方法必须返回一些东西
    猜你喜欢
    • 2021-06-05
    • 2015-05-30
    • 2021-12-01
    • 2021-09-22
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    相关资源
    最近更新 更多