Illegal start of expression (method) [closed]

限于喜欢 提交于 2019-12-09 03:58:30

问题


decided to recently learn a little bit of java and I've been stumped at the first hurdle. Here is my extremely basic code:

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) {
    }
}
}

As far as I can see, there are no errors. However, at compile time I receive this error:

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

I've searched and searched and all the usual responses are typos and misplaced brackets but as far as I can see this isn't the case.

Not sure if it will make any difference but I am on a mac, using the vim editor and I'm compiling from terminal.

Any advice is appreciated.


回答1:


funcName is being defined from within the main method, it must be outside it:

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:


You cannot declare a method inside another method. Move funcName outside of main method:

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;
    }
}


来源:https://stackoverflow.com/questions/26982979/illegal-start-of-expression-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!