gpt4 book ai didi

java - 当我没有 main 方法时我的程序如何运行

转载 作者:行者123 更新时间:2023-12-02 03:13:18 24 4
gpt4 key购买 nike

我正在大学学习java类(class),我们正在使用一个名为acm的库。但是当我们编写代码时,我们不会创建 main 方法。 “public void run(){}”充当主方法。请解释一下。

以下是我创建的一个程序的示例。

import acm.program.ConsoleProgram;
import acm.util.RandomGenerator;

public class Assignment3 extends ConsoleProgram {

private static final long serialVersionUID = 1L;
private RandomGenerator rgen = RandomGenerator.getInstance();

public void run() {
final int QUESTION_AMOUNT = 5;

println("Welcome to the Math Quiz! You have " + QUESTION_AMOUNT + " questions to answer! Good luck!");

for (int i = 0; i < QUESTION_AMOUNT; i++) {
askQuestion();
}

println("End of the quiz!");
}

public void askQuestion() {
int num1, num2, kidanswer, realanswer;
String operation = "";
boolean x = rgen.nextBoolean();

if (x == true) {
operation = "+";
} else {
operation = "-";
}

if (operation == "-") {
num1 = rgen.nextInt(0, 20);
num2 = rgen.nextInt(0, num1);
} else {
num1 = rgen.nextInt(0, 20);
num2 = rgen.nextInt(0, 20 - num1);
}

String question = ("What is " + num1 + " " + operation + " " + num2 + " = ");

if (operation == "-") {
realanswer = num1 - num2;
} else {
realanswer = num1 + num2;
}

kidanswer = readInt(question);

int i = 0;
while (i < 2) {
if (kidanswer == realanswer) {
println("That is correct! Well done!");
break;
} else {
kidanswer = readInt("Wrong answer. Please try another answer: ");
i++;
if (i == 2) {
if (kidanswer == realanswer) {
println("That is correct! Well done!");
} else {
println("Sorry :( Out of tries! The answer was: " + realanswer);

}
}
}
}
}
}

最佳答案

因为:

关于java - 当我没有 main 方法时我的程序如何运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40738381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com