Java运行程序
这是一个非常简单的程序。 我已经创建了一个新类,我将定义一个新方法,以便在下一个新类中调用Java运行程序,java,Java,这是一个非常简单的程序。 我已经创建了一个新类,我将定义一个新方法,以便在下一个新类中调用 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
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
不能将方法声明为方法 这样做:
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.");
}
}
不能将方法声明为方法 这样做:
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.");
}
}
错误是因为您在另一个方法中声明了一个方法,它是
main()
更改此项:
public static void main(String[] args) {
int number = 1;
public void showSomething(){
System.out.println("This is my method "+number+" created by me.");
}
}
到
由于
main()
是static
,因此showSomething()
也应该声明为static
。只有静态方法
可以从另一个静态方法
调用。错误是因为您在另一个方法中声明了一个方法,它是main()
更改此项:
public static void main(String[] args) {
int number = 1;
public void showSomething(){
System.out.println("This is my method "+number+" created by me.");
}
}
到
由于main()
是static
,因此showSomething()
也应该声明为static
。只有静态方法
可以从另一个调用静态方法
应该是这样的(在主方法之外定义方法)
应该是这样的(在main之外定义方法)
无法在主程序中创建方法。 相反,你应该这样做:
public class MyClass {
public static void main(String[] args) {
showSomething();//this calls showSomething
}
public void showSomething(){
int number = 1;
System.out.println("This is my method "+number+" created by me.");
}
}
在您的类中,您有一个运行程序的main方法。在同一级别上,您还有其他要在程序中使用的方法或变量。您不能在主程序中创建方法。 相反,你应该这样做:
public class MyClass {
public static void main(String[] args) {
showSomething();//this calls showSomething
}
public void showSomething(){
int number = 1;
System.out.println("This is my method "+number+" created by me.");
}
}
在您的类中,您有一个运行程序的main方法。在同一级别上,您还需要在程序中使用其他方法或变量。showSomething()需要在main()之外定义。您希望代码做什么?在另一个方法中有一个方法。为什么?showSomething()需要在main()之外定义,您希望代码做什么?在另一个方法中有一个方法。为什么?@ArnaudDenoyelle为这个错误感到抱歉。编辑我的answer@ArnaudDenoyelle对不起,弄错了。编辑我的回答非常感谢你的关注。
public class MyClass {
public static void main(String[] args) {
showSomething();//this calls showSomething
}
public void showSomething(){
int number = 1;
System.out.println("This is my method "+number+" created by me.");
}
}