Java运行程序

时间:2014-11-25 15:34:42

标签: 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.");
        }

    }
}

但是,当我运行这个程序时,我遇到了一个错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    Syntax error on token(s), misplaced construct(s)
    Syntax error on token "void", @ expected

6 个答案:

答案 0 :(得分:3)

错误是因为你在另一个方法中声明了一个方法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

答案 1 :(得分:2)

您无法将方法声明为方法。

这样做:

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.");
  }
}

答案 2 :(得分:1)

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.");
}

}

答案 3 :(得分:0)

应该是这样的(定义主要的方法),

public class MyClass {


    public static void showSomething(int number){
            System.out.println("This is my method "+number+" created by me.");
    }

    public static void main(String[] args) {
        int number = 1;
        showSomething(number);
    }
}

答案 4 :(得分:0)

您无法在主内部创建方法。 而是这样做:

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.");
    }
}

在您的班级中,您有一个运行该程序的主方法。在同一级别,您可以在程序中使用其他方法或变量。

答案 5 :(得分:-1)

public class MyClass {

    public static void main(String[] args) {
        int number = 1;
        showSomething(number
    }

    public void showSomething(int number){
        System.out.println("This is my method "+number+" created by me.");
    }
}