java - java中构造函数的问题

标签 java constructor

所以我的主类中有这个构造函数:

public class GCTest extends Program {
    GCTest(int x, int y) {
        int gcd = gcd(Math.abs(x), Math.abs(y));
        int num = x / gcd;
        int den = Math.abs(y) / gcd;
        if (y < 0) num = -num;
    }
}

当我在 void run() 中调用构造函数时,当我编译它时,cmd 会给出以下错误“无法确定主类”,但是当我创建一个仅包含构造函数的新 java 文件并进行编译时他们使用.;命令程序运行良好。我究竟做错了什么?我对编程有点陌生。提前致谢!

import java.lang.Runtime;
import acm.program.*;

public class GCTest extends Program {
    GCTest(int x, int y){
        int gcd = gcd(Math.abs(x), Math.abs(y));
        int num = x / gcd;
        int den = Math.abs(y) / gcd;
        if (y < 0) num = -num;
    }

    public int gcd(int a, int b) {
        if (b == 0) return a;
        return gcd(b,a%b);
    }

    public void run() {
        Runtime myRuntime = Runtime.getRuntime();

        println("Allocating 10000 Rational objects.");

        for(int i = 0; i < 10000; i++){
            new GCTest(i + 1, i + 2);
        }

        long fB = myRuntime.freeMemory();
        println("Free memory before garbage collection = " + fB);
        myRuntime.gc();

        long fA = myRuntime.freeMemory();
        println("Free memory after garbage collection = " + fA);
        println("Garbage collection freed up " + (fA - fB) + " bytes.");
    }
}

当我编译并运行发布的程序时,我收到“无法确定主类错误”。 当我用这个 Rational.java 编译我的 GCTest.java 时(在我从 GCTest 代码中删除构造函数并用 new Rational( , ) 替换 new GCTest 之后)一切都运行良好。这是 Rational.java :

public class Rational{
public Rational(int x, int y) {
  int gcd = gcd(Math.abs(x), Math.abs(y));
  int num = x / gcd;
  int den = Math.abs(y) / gcd;
  if (y < 0) num = -num;
}
public int gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b,a%b);
}
}

最佳答案

当您忘记包含 main 方法时,您通常会看到此错误:

public static void main(String[] args)

在你的程序中,你做到了。尝试这样的事情:

public class GCTest extends Program {
   ..
   ..
   public static void main(String[] args) { 
       new GCTest(...).run();
   }

}

main(..) 是一个特殊的方法,它告诉 Java 程序从哪里开始。

关于java - java中构造函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20889601/

相关文章:

c++ - 使用另一个类的静态成员函数时构造函数中的未解析静态符号。

javascript - 让构造函数返回 Promise 是不好的做法吗?

c++ - 使用子类调用主类中的函数

java - ZipFile 和 ZipEntry 类 : CENATT, CENATX、CENCOM、CENCRC、CENDSK 等中的这些字段是什么?

java - java中如何封装多个类?

java - 如何在 MySQL 中创建临时过程?

python - Leetcode 的两个和错误 __init__() 缺少 2 个位置参数

java - 启动时 EnvironmentPostProcessor 实现类中的 Autowired 属性为 null

java - 正则表达式删除最后一个括号内的内容

c++ - 在 C++ 中初始化自定义类的 vector