gpt4 book ai didi

用于结帐的 Java 练习

转载 作者:行者123 更新时间:2023-11-30 06:36:16 27 4
gpt4 key购买 nike

我最近尝试了一些 Java,希望对我的风格进行一些评论。如果你喜欢看这个放在图像中的练习,并告诉我我的风格是否足够好?或者是做的还不够好,可以告诉我应该在哪方面多下工夫,帮我改进一下?

exercise for my question

/*
* File: MathQuiz.java
*
* This program produces Math Quiz.
*/
import acm.program.*;
import acm.util.*;

public class MathQuiz extends ConsoleProgram {

/* Class constants for Quiz settings. */
private static final int CHANCES = 3;
private static final int QUESTIONS = 5;
private static final int MIN = 0;
private static final int MAX = 20;

/* Start program. Number of questions to ask is assigned here. */
public void run() {
println("Welcome to Math Quiz");
while(answered != QUESTIONS) {
produceNumbers();
askForAnswer();
}
println("End of program.");
}

/* Ask for answer, and check them. Number of chances includes
* first one, where user is asked for reply. */
private void askForAnswer() {
int answer = -1;
if(type)
answer = readInt("What is " + x + "+" + y + "?");
else
answer = readInt("What is " + x + "-" + y + "?");
for(int i = 1; i < CHANCES+1; i++) {
if(answer != solution) {
if(i == CHANCES) {
println("No. The answer is " + solution + ".");
break;
}
answer = readInt("That's incorrect - try a different answer: ");
} else {
println("That's the answer!");
break;
}
}
answered++;
}

/* Produces type and two numbers until they qualify. */
private void produceNumbers() {
produceType();
produceFirst();
produceSecond();
if(type)
while(x+y >= MAX) {
produceFirst();
produceSecond();
}
else
while(x-y <= MIN) {
produceFirst();
produceSecond();
}
calculateSolution();
}

/* Calculates equation solution. */
private void calculateSolution() {
if(type) solution = x + y;
else solution = x - y;
}

/* Type of the equation. True is from plus, false is for minus. */
private void produceType() {
type = rgen.nextBoolean();
}

/* Produces first number. */
private void produceFirst() {
x = rgen.nextInt(0, 20);
}

/* Produces second number. */
private void produceSecond() {
y = rgen.nextInt(0, 20);
}

/* Class variables for numbers and type of the equation. */
private static boolean type;
private static int x;
private static int y;

/* Class variables for equation solution. */
private static int solution;

/* Class variable counting number of answered equations,
* so if it reaches number of provided questions, it ends */
private static int answered = 0;

/* Random generator constructor. */
RandomGenerator rgen = new RandomGenerator();

}

最佳答案

我注意到的一件事是,您的所有方法都没有参数并返回 void。

我认为如果使用方法参数和返回值来显示程序中的数据流,而不是使用对象的状态来存储所有内容,情况会更清楚。

关于用于结帐的 Java 练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5053990/

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