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

    }
}

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

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) 个答案

  1. # 1 楼答案

    错误是因为您在另一个方法中声明了一个方法,它是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 method调用static methods

  2. # 2 楼答案

    你不能在你的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.");
        }
    }
    

    在你的课堂上,你有一个运行程序的主方法。在同一级别上,您还有其他要在程序中使用的方法或变量

  3. # 3 楼答案

    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.");
        }
    }
    
  4. # 4 楼答案

    应该是这样的(定义主方法之外的方法)

    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);
        }
    }
    
  5. # 5 楼答案

    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.");
    }
    
    }
    
  6. # 6 楼答案

    不能将方法声明为方法

    这样做:

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