错误::在课程中找不到主要方法

时间:2017-05-20 13:35:14

标签: java

当我运行我的代码时,收到此错误消息:

Error: Main method not found in class "Class name", please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

我的代码:

public static void main(String[] args){
    public void printPhoto(int width,int height, boolean inColor){
        System.out.println("Width = " + width +  " cm" );
        System.out.println("Height = " + height + " cm");
        if(inColor){
            System.out.println("Print is Full color.");
        } else {
            System.out.println("Print is black and white.");
        }
        printPhoto(10,20,false);
    }
}

2 个答案:

答案 0 :(得分:2)

要启动一个java程序,你需要在代码中没有定义的main方法,你可以这样做:

public class Test {

    public void printPhoto(int width, int height, boolean inColor) {
        System.out.println("Width = " + width + " cm");
        System.out.println("Height = " + height + " cm");
        if (inColor) {
            System.out.println("Print is Full color.");
        } else {
            System.out.println("Print is black and white.");
        }
        // printPhoto(10, 20, false); // Avoid a Stack Overflow due the recursive call
    }

    //main class
    public static void main(String[] args) {
        Test tst = new Test();//create a new instance of your class
        tst.printPhoto(0, 0, true);//call your method with some values        
    }

}

答案 1 :(得分:0)

已发布@YCF_L,您需要使用main方法。

首先,请确保删除:

printPhoto(10,20,false);

以避免因递归调用而导致堆栈溢出。

如果您需要创建新实例并直接使用您的方法,您可以执行以下操作:

public class Test {

    public Test printPhoto(int width, int height, boolean inColor) {
        System.out.println("Width = " + width + " cm");
        System.out.println("Height = " + height + " cm");
        if (inColor) {
            System.out.println("Print is Full color.");
        } else {
            System.out.println("Print is black and white.");
        }
        return this;
    }

    public static void main(String[] args) {
        Test testObj = new Test().printPhoto(10, 20, false); //Creates a new instance of your class Test and calls the method printPhoto
    }

}

或者,你也可以将方法设为静态,但它并不总是最好的程序,它取决于你将如何使用它。

public class Test {

    public static void printPhoto(int width, int height, boolean inColor) {
        System.out.println("Width = " + width + " cm");
        System.out.println("Height = " + height + " cm");
        if (inColor) {
            System.out.println("Print is Full color.");
        } else {
            System.out.println("Print is black and white.");
        }
    }

    public static void main(String[] args) {
        printPhoto(10, 20, false);
    }

}