所以我的主类中有这个构造函数:
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/