问题
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