gpt4 book ai didi

java - 简单的数学游戏

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

这是我的第一个问题,请耐心等待:-)我尝试编写非常简单的 Java 游戏。首先,我想生成一个示例任务,例如“2+2 =”。用户必须回答结果是什么。接下来我想生成一个字符和其他随机数。

2 +2 = (4) if answer == result, than generate random char nad number 4 - 1 = (3) if answer == result, than generate random char nad number 3 + 5 = (9)

目前我陷入了角色生成的困境。

import java.util.Random;


public class Main {
public static void main(String[] args) {
Random randomNumber = new Random();
int userRandomNumber = randomNumber.nextInt(10) - 1;
int myRandomNumber = randomNumber.nextInt(10) - 1;
int i = giveResult(userRandomNumber, myRandomNumber);
System.out.println(userRandomNumber);
System.out.println(myRandomNumber);
System.out.println(i);

}

public static int giveResult(int userRandomNumber, int myRandomNumber) {

Random randomNumber2 = new Random();
int switchRandomNumber = randomNumber2.nextInt(2);
char operatorRandom = '+';
int result = 0;

switch (switchRandomNumber) {
case 1:
operatorRandom = '+';
result = userRandomNumber + myRandomNumber;
//return result;
break;
case 2:
operatorRandom = '-';
result = userRandomNumber - myRandomNumber;
//return result;
break;
default:
result = 0;

}
return result;
}
}

如何更正我的代码以及后续步骤做什么?

问候!

最佳答案

您使该程序变得比实际需要的更加复杂。

实现您的目标(或至少我认为您的目标)的最简单方法如下:

public static void main(String[] args) {
Random rand = new Random();
int NumberOfAnswers = addOrSubtract.length;
int pick = rand.nextInt(NumberOfAnswers);
choice = addOrSubtract[pick];
int randomNumber1 = rand.nextInt(10);
int randomNumber2 = rand.nextInt(10);
if (choice == "+") {
answer = randomNumber1 + randomNumber2;
} else {
answer = randomNumber1 - randomNumber2;
}
System.out.println(randomNumber1 + " " + choice + " " + randomNumber2 + " = ");
Scanner input = new Scanner(System.in);
int inputAnswer = input.nextInt();
if (inputAnswer == answer) {
System.out.println("Correct! The answer was: " + answer);
main(null);
} else {
System.out.println("Incorrect. The answer was: " + answer);
System.out.println("Good-Bye!");
System.exit(0);
}
input.close();
}

注意:我几乎完全重新完成了您的程序,因此如果您对任何内容有任何疑问,请在下面评论。

关于java - 简单的数学游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43304545/

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