我正在做一个类似于 Cows and Bulls 的 Java 游戏。但不是显示“Cow”和“Bull”,而是显示“MOO”或“moo”。生成一个 4 位数字,用户可以猜到。对于正确指定的每个数字(相同的数字,相同的位置),屏幕上会显示一个“MOO”。对于每个被猜到的具有相同数字但位置错误的数字,都会显示一个“moo”。我在执行返回多少“moo”的方法时遇到了麻烦。
public int getLittleMooCount(int guess)
{
int count = 0;
String guessString = Integer.toString(guess);
String randomValueString = Integer.toString(randomValue);
// Pads the number with zero if less than 4 digits, so length is always 4
while(guessString.length() < 4)
{
guessString = "0" + guessString;
}
while(randomValueString.length() < 4)
{
randomValueString = "0" + randomValueString;
}
// checking to see if positions EXACTLY match. If so, it would return a MOO (the getBigMoo
// Count is in my other method)
for (int i = 0; i < 4; i++)
{
if (guessString.charAt(i) == randomValueString.charAt(i))
{
randomValueString = randomValueString.replace(randomValueString.charAt(i), 'X');
guessString = guessString.replace(guessString.charAt(i), 'O');
}
}
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (guessString.charAt(j) == randomValueString.charAt(i))
{
count++;
randomValueString = randomValueString.replace(randomValueString.charAt(i), 'X');
guessString = guessString.replace(guessString.charAt(j), 'O');
}
}
}
return count;
}
- 测试输入
- 0011
- 2233
- 4455
- 6677
- 8899
- 1234
- 5678
- 9090
随机数为 5509 的结果
- 1 moo = 正确
- 没有=正确
- 1 moo = 错误!应该是两个哞。
- 没有=正确
- 1 MOO = 正确
- 没有=正确
- 1 MOO = 正确
- 2 moo = 正确
似乎它适用于某些数字,但对于其他数字,总是有一个测试数据是错误的。显然,出了点问题,但我尝试了一切,这令人沮丧!如果有帮助,我可以发布另一个示例。
我在这里先向您的帮助表示感谢!
编辑:好吧,我把它改成了一个字符数组,现在它什么也没做。我可以发誓我做对了。
int count = 0;
String guessString = Integer.toString(guess);
String randomValueString = Integer.toString(randomValue);
char [] randomValueCharacter = randomValueString.toCharArray();
char [] guessCharacter = guessString.toCharArray();
while(guessString.length() < 4)
{
guessString = "0" + guessString;
}
while(randomValueString.length() < 4)
{
randomValueString = "0" + randomValueString;
}
for (int i = 0; i < 4; i++)
{
if (guessString.charAt(i) == randomValueString.charAt(i))
{
randomValueCharacter[i] = 'X';
guessCharacter[i] = 'O';
}
}
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (guessString.charAt(j) == randomValueString.charAt(i))
{
count++;
randomValueCharacter[i] = 'X';
guessCharacter[j] = 'O';
}
}
}
return count;
}