繁体   English   中英

Java类没有main方法

[英]Java class doesn't have main method

我需要为GCD运行一个方法代码。 我的java文件名为“GCD.java”,公共类称为“GCD”。 然而,我仍然收到消息“GCD类没有主要方法”,即使我的任何一行都没有红色的解释点圈。 我可以在没有方法代码的情况下运行代码(即public static void main(String [] args)),但我需要使用方法运行代码。 谢谢。

==========================

import java.util.Scanner;

    public class GCD
    {

        public static int getDivisor(int x, int y)
        {


        System.out.println("Greatest Common Divisor Finder");
        System.out.println();

        String choice = "y";
        Scanner sc = new Scanner(System.in);
        while (choice.equalsIgnoreCase("y"))
        {

            System.out.print("Enter first number: ");
            x = sc.nextInt();
            System.out.print("Enter second number: ");
            y = sc.nextInt();

            int secondNumber = 0;
            int firstNumber = 0;
            int Greatestcommondivisionfinder = 0;

            // x = first,  y = second
            if (x > y)
                {
                    do
        {
                        x -= y;
                        }
             while (x > y);
        do
        {
                        y -= x;
                        }
    while (y > 0);
            System.out.println("Greatest Common Divisor: " + x);
        }

            else if (y > x)
        {
        do
                        {
            y -= x;
                        }
    while(y > x);
        do
                        {
            x -= y;
                        }
    while (x > 0);
            System.out.println("Greatest Common Divisor: " + y);
        }
             else
                    {
                    int subtract;
                    do
                    {
                    subtract = (int)y - (int)x;
                    }

            while(y > x);
            int gcd;
            gcd = (int)x - subtract;
                    }


            System.out.println();
            System.out.print("Continue? (y/n): ");
            choice = sc.next();
            System.out.println();
                }
            return 0;
          }
    }

它对于没有main方法的类是完全有效的 - 或者它有一个未声明为public static void main(String[] args)的main方法。

但是,为了将类视为Java应用程序的入口点 ,它需要具有该签名的方法(尽管参数名称可以变化)。

所以基本上,你有一个本身很好的课程,但你不能独立发布。 你可以创建一个单独的类,例如

public class GcdLauncher {
    public static void main(String[] args) {
        GCD.getDivisor(0, 0); // Parameters are ignored anyway...
    }
}

然后编译后你可以运行:

java GcdLauncher

或者您可以向GCD类添加public static void main(String[] args)方法。

我强烈建议你改变你的getDivisor方法不要有参数 - 你实际上并没有使用它们......

如果要将您的类用作主程序,则必须实现一个

public static void main(String[] args))

从中可以调用GCD方法的方法。

是的,正如您的Eclipse正确地说的那样,您的GCD.java文件中没有main方法。 为了独立运行这个类,你需要有main方法。 否则,您只能创建此类的Object并从其他类调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM