我在弄清楚我的代码中发生的事情时遇到了一些麻烦(Go figure ...) 我还没有涉及到一些最终的int值,但是在我能解决其他一些问题之后我会想到。
我无法弄清楚为什么在将correctGuess更改为true后,我无法在程序退出之前从我的用户那里收到更多输入,以决定是否继续玩。
这应该花费毫秒来自某人的计算机,并在1-110之间收集一个随机数,但有时我会得到负数,似乎无法弄清楚问题是什么。
< / LI> 醇>任何帮助将不胜感激......
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
private static final int MIN_NUMBER = 1;
private static final int MAX_NUMBER = 110;
private static final int EXIT_VALUE = -1;
private static final int MAX_GAMES = 256;
public static void main(String[] argv) {
System.out.println("*** You are playing the CSC110 Guessing Game ***");
Scanner scanner = new Scanner(System.in);
int totalGames = 0;
int wonGames = 0;
int guess = 0;
boolean playing = true;
while (playing) {
boolean correctGuess = false;
totalGames++;
Random rg = new Random(System.currentTimeMillis());
int n = MIN_NUMBER + rg.nextInt() % (MAX_NUMBER - MIN_NUMBER);
System.out.println("Pick a number between 1 and 110 (-1 to exit): ");
int numberOfTries = 0;
while (!correctGuess)
{
guess = scanner.nextInt();
numberOfTries++;
System.out.print(numberOfTries);
if (guess == n) {
System.out.print("Congrats, it took you " + numberOfTries + " try/tries to get the right number!");
System.out.print("Do you want to play again? (Yes/No)");
correctGuess = true;
}
else if(guess != n && numberOfTries < 5)
{
System.out.println("nope... \n");
}
else if(guess > n && numberOfTries >= 5)
{
System.out.print("Try something lower \n");
}
else if(guess < n && numberOfTries >= 5)
{
System.out.print("Try something higher \n");
}
}
String playAgain = scanner.nextLine();
if(playAgain.equals("Yes"))
{
playing = true;
}
else
{
playing = false;
}
}
}
}
答案 0 :(得分:1)
1:使用以下测试并且它正常工作:
String playAgain = scanner.next();
您也可以考虑修改if语句,如下所示:
if(playAgain.equalsIgnoreCase("Yes") || playAgain.equalsIgnoreCase("Y"))
2:确保数字正确的最简单方法是使用Math.abs()。
int n = Math.abs(MIN_NUMBER + rg.nextInt() % (MAX_NUMBER - MIN_NUMBER));