gpt4 book ai didi

java - 修复无限循环?

转载 作者:行者123 更新时间:2023-12-01 18:52:36 25 4
gpt4 key购买 nike

我是计算机科学专业的一年级学生,在类里面我们有一个项目,我们为名为“Bagels”的游戏制定算法。我们要随机生成一个 3 位数字,但所有数字不能是相同的数字。因此,像“100、220、343 和 522”这样的数字是非法的,因为它们包含具有相同数字的数字。

我决定最好单独生成每个数字,比较每个数字并根据需要进行更改,然后将每个数字添加到字符串中。这是我的代码:

Scanner input = new Scanner(System.in);

// Generate a random 3 digit number between 102 and 987. The bounds are 102 to 987 because each
// digit in the number must be different. The generated number will be called SecretNum and be
// stored as a String.

// The First digit is generated between 1 and 9 while the second and third digit are generated
// between 0 and 9.

String SecretNum = "";
int firstDigit = (int)(Math.random() * 9 + 1);
int secondDigit = (int)(Math.random() * 10);
int thirdDigit = (int)(Math.random() * 10);

// Now the program checks to see if any of the digits share the same value and if one digit shares
// the same value then the number is generated repeatedly until the value is different

// Digit tests are used to determine whether or not any of the digits share the same value.
boolean firstDigitTest = (firstDigit == secondDigit) || (firstDigit == thirdDigit);

boolean secondDigitTest = (secondDigit == firstDigit) || (secondDigit == thirdDigit);

boolean thirdDigitTest = (thirdDigit == firstDigit) || (thirdDigit == secondDigit);

if (firstDigitTest){
do{
firstDigit = (int)(Math.random() * 9 + 1);
}while (firstDigitTest);

} else if (secondDigitTest){
do{
secondDigit = (int)(Math.random() * 10);
}while(secondDigitTest);

} else if (thirdDigitTest){
do{
thirdDigit = (int)(Math.random() * 10);
}while(thirdDigitTest);
}// end if statements

// Now the program will place each digit into their respective places
SecretNum = firstDigit + "" + secondDigit + "" + thirdDigit;

System.out.println(SecretNum);

(暂时忽略扫描仪;这部分不需要它,但稍后我会需要它)

不幸的是,当我测试这些数字以查看是否有相同的数字时,我有时会陷入无限循环。棘手的部分是,有时它会像无限循环一样运行,但会在我终止程序之前生成数字。所以有时如果它处于无限循环中,我不确定它是否真的处于无限循环中或者我不耐烦,但我确定这是一个无限循环问题,因为我等了大约10分钟,程序仍在运行。

我真的不确定为什么它会变成无限循环,因为如果碰巧一个数字与另一个数字匹配,那么应该不断生成该数字,直到它是一个不同的数字,所以我不明白它是如何变成无限循环的。这就是我需要帮助的地方。

(哦,我制作字符串的方式并不代表我将如何保留它。一旦我修复了这个循环,我就会更改它,以便将数字附加到字符串中。)

最佳答案

问题在于(例如)firstDigitTest 设置为特定的 boolean 值,truefalse,并且从未更改。即使您将 firstDigit 设置为不同的值,从而解决了 firstDigitTest 检测到的问题,您也不会重新更新 firstDigitTest 来检测是否问题仍然存在。因此,您的每个循环(如果确实输入了)都将无限循环。

我认为您不妨消除 boolean 变量,然后循环 while(firstDigit == secondaryDigit ||firstDigit ==thirdDigit || secondaryDigit ==thirdDigit)

关于java - 修复无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15315492/

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