java 表达式的非法开始(方法)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26982979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Illegal start of expression (method)
提问by Dominic Sore
decided to recently learn a little bit of java and I've been stumped at the first hurdle. Here is my extremely basic code:
最近决定学习一点 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) {
}
}
}
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.
不确定它是否会有任何不同,但我在 Mac 上,使用 vim 编辑器,我正在从终端编译。
Any advice is appreciated.
任何建议表示赞赏。
回答by badjr
funcName
is being defined from within the main method, it must be outside it:
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) {
}
}
回答by Luiggi Mendoza
You cannot declare a method inside another method. Move funcName
outside of main
method:
您不能在另一个方法中声明一个方法。移动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;
}
}