gpt4 book ai didi

java - 加法游戏栅栏柱问题,加法符号显示在等式之前

转载 作者:行者123 更新时间:2023-11-30 07:49:29 25 4
gpt4 key购买 nike

我正在制作一个加法游戏,但我遇到的唯一问题是加法符号不断出现在问题之前,即使它前面没有数字。解决这个问题最简单的方法是什么?

  package addgame;
import java.util.Random;
import java.util.Scanner;
public class AddingGame {
private static Scanner console;

public static void main (String[]args) {
System.out.println("We are going to play an adding game, you have 3 tries. Type your answer.");
equation();
}
public static void equation() {
int tries = 5;
int points=0;
Random rand = new Random ();
while (tries>=3) {
int totalnums = rand.nextInt(4)+1;
int sumAns=0;
for (int i=1; i<=totalnums+1;i++) {
int nums= rand.nextInt(10)+1;
System.out.print(" + "+nums );
sumAns+=nums;
}
System.out.print(" = ");
console = new Scanner (System.in);
int ans = console.nextInt();
if(ans!=sumAns) {
tries--;
}
else if(tries>=3) {
points++;
}
if(tries<3) {
System.out.println("Game Over...");
System.out.println("Points="+points+"\nBetter luck next time!");

}
}

}
}

最佳答案

除了您发布的内容之外,这里还有几个问题。

首先,当只有 3 次尝试时,不要使用 attempts = 5。这还不清楚。如果您或其他人稍后必须查看该计划怎么办?你知道“tries = 5”是什么意思吗?

如果你说类似的话

int triesLeft = 3;

歧义要少得多。从 3 开始,您的 while 语句也更加简单。

while (triesLeft > 0) {

同样,你想要添加多少个数字也有点不清楚。正如您所注意到的,如果您要添加的数字数量是 0 或 1,那么在加法游戏中就会出现问题。您的解决方案确实有效。但是,如果您这样做...(我也在这段代码中包含了您的问题的一种可能的解决方案。)

int numberOfAddends = rand.nextInt(4)+2;  //This assumes the maximum number of numbers you want to add is 5 (i.e. 3 + 2), and the minimum number is 2.
int sumAns = rand.nextInt(10)+1; //Now note these two lines.
System.out.print(sumAns); //this will make sure the first number is printed before the + sign

for (int i=1; i < numberOfAddends;i++) {
//the inside of this for loop can stay the same.
}

请注意,现在更容易判断发生了什么。是否有任何方法可以使其更加清晰,可能值得考虑。

过了这一点,您的代码实际上只是一些小事情。

while(triesLeft > 0) {
.
.
.
if(ans!=sumAns) {
tries--;
}
else { //the check you specified was only ever reachable when the condition you were checking is true. What you wrote was equivalent to else if (true).
points++;
}
}
System.out.println("Game Over..."); //You don't need a check for this when it is placed outside the while loop.
System.out.println("Points="+points+"\nBetter luck next time!");

关于java - 加法游戏栅栏柱问题,加法符号显示在等式之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33468182/

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