这是一个非常简单的程序。我已经创建了一个新的类,我将定义一个新的方法来回忆一个新类中的下一步。
public class MyClass {
public static void main(String[] args) {
int number = 1;
public void showSomething(){
System.out.println("This is my method "+number+" created by me.");
}
}
}但是,当我运行这个程序时,我遇到了一个错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token(s), misplaced construct(s)
Syntax error on token "void", @ expected发布于 2014-11-25 15:38:09
错误是因为您在这里的另一个方法-- main()中声明一个方法。
改变这一点:
public static void main(String[] args) {
int number = 1;
public void showSomething(){
System.out.println("This is my method "+number+" created by me.");
}
}至
public static void main(String[] args) {
int number = 1;
showSomething(); // call the method showSomething()
}
public static void showSomething(){
System.out.println("This is my method "+number+" created by me.");
}另外,showSomething()应该声明为static,因为main()是static。只能从另一个static methods调用static method。
发布于 2014-11-25 15:38:01
不能将方法声明为方法。
这样做吧:
public class MyClass {
public static void main(String[] args) {
int number = 1;
showSomething(number);
}
public static void showSomething(int number){
System.out.println("This is my method "+number+" created by me.");
}
}发布于 2014-11-25 15:38:03
public class MyClass {
public static void main(String[] args) {
new MyClass().showSomething();
}
public void showSomething(){
int number = 1;
System.out.println("This is my method "+number+" created by me.");
}
}https://stackoverflow.com/questions/27130752
复制相似问题