这是我在这里的第一篇文章,如果这是一个偏离主题的主题,或者我对细节的介绍很粗糙,请提前道歉。我正在自学Java并写了一些代码来试验定义一个引用类型和作用于它的方法,虽然它有效,但我不知道是否有更好,更有效的方法来完成我所做的事情。我想要至少一个返回值的方法(这里检查问题的答案是否正确),并使用静态变量来跟踪在生成多个类实例的过程中发生的事情(这里跟踪回答的问题数量)并且数字正确回答)。该代码生成一个分区问题的测验。
以下是代码,也发布在GitHub:
使用除数btw 5和14以及商btw 2和11定义引用类型DivisionProblem,使用方法生成问题的值,在控制台中说明问题(如果有帮助,我使用Eclipse),检查答案是否正确,采取正确和错误的答案,并追踪整体表现:
import java.util.Random;
class DivisionProblem {
int dividend, divisor, quotient;
static int answered=0, answeredRight=0;
void generate() {
Random myRandom = new Random();
divisor = myRandom.nextInt(10) + 5;
quotient = myRandom.nextInt(10) + 2;
dividend=divisor*quotient;
}
void stateProblem() {
System.out.print("What is " + dividend + " divided by " + quotient + "?");
}
boolean checkAnswerTF(int answer) {
return answer == divisor;
}
void rightAnswer() {
++answered;
++answeredRight;
System.out.println("That's right!");
}
void wrongAnswer() {
++answered;
System.out.println("No, the answer is "+ divisor);
}
void statePerformance() {
System.out.print("You have answered " + answeredRight + " of " + answered + " questions correctly. ");
}
}
这是使用DivisionProblem类型的类:
import java.util.Random;
import java.util.Scanner;
public class DivisionQuiz {
public static void main(String[] args) {
char reply;
Scanner keyboard = new Scanner(System.in);
DivisionProblem aDivisionProblem;
do {
aDivisionProblem = new DivisionProblem();
aDivisionProblem.generate();
aDivisionProblem.stateProblem();
if (aDivisionProblem.checkAnswerTF(keyboard.nextInt())) {
aDivisionProblem.rightAnswer();
} else {
aDivisionProblem.wrongAnswer();
};
aDivisionProblem.statePerformance();
System.out.println("Another problem? Type Y for yes.");
reply = keyboard.findWithinHorizon(".", 0).charAt(0);
} while (reply == 'Y'||reply == 'y');
keyboard.close();
}
}
以下是示例输出:
What is 112 divided by 8?14
That's right!
You have answered 1 of 1 questions correctly. Another problem? Type Y for yes.
y
What is 80 divided by 8?10
That's right!
You have answered 2 of 2 questions correctly. Another problem? Type Y for yes.
y
What is 130 divided by 10?12
No, the answer is 13
You have answered 2 of 3 questions correctly. Another problem? Type Y for yes.
y
What is 21 divided by 3?7
That's right!
You have answered 3 of 4 questions correctly. Another problem? Type Y for yes.
n
欢迎提出任何改进建议。我正在考虑学习JavaFX并将其从Eclipse控制台中取出来。