我知道之前已经问过同样的事情,但是我很难让这个人工作。编辑:它现在似乎只是无限期地继续运行。我不再收到错误,但代码会一直运行直到我停止运行。
现在我的代码:
import java.util.Scanner;
public class Guess2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Scanner outScan = new Scanner (System.in);
boolean input = true;
while (input == true) {
System.out.println(
"Gimme a number, any number. This number will be the maximum\n"
+ " in a range of numbers. Your goal is to guess\n"
+ " the number that I have picked at random"
+ " within this range. Then, enter how many"
+ " guesses you would like to receive.");
int max = scan.nextInt();
int meGuess = scan.nextInt();
// Round whatever random number is generated
double randomNumber =
(int) Math.round((max * Math.random()) + 1);
randomNumber = (int) randomNumber;
System.out.println("Alright now guess which number I picked.");
int numGuess = 0;
while (numGuess <= meGuess)
{
int guess = scan.nextInt();
if (guess < randomNumber)
{
System.out.println("Too low, my friend.");
numGuess++;
} else if (guess == randomNumber)
{
numGuess++;
System.out.print(
"Wowee Zowee! You got it right! AI "
+ "will absolutely never sufficiently replace "
+ "human intellect.\n"
+ "It only took you "
+ numGuess);
if (numGuess == 1)
{
System.out.println(" try.");
} else
{
System.out.println(" tries.");
}
System.out.println("Do you want to play again? Y/N");
String answer = outScan.nextLine();
input = answer.equalsIgnoreCase("y");
numGuess = 0;
meGuess = 0;
max = 0;
} else if (guess > randomNumber)
{
System.out.println("Too high, buddy.");
numGuess++;
}
if (numGuess > meGuess)
{
System.out
.println("Sorry buddy, you used up more"
+ " guesses than you told me to give you."
+ " Maybe next time.");
System.out.println("Do you want to play again? Y/N");
String answer = outScan.nextLine();
input = answer.equalsIgnoreCase("y");
numGuess = 0;
meGuess = 0;
max = 0;
}
}
scan.close();
outScan.close();
}}
}
一些背景
我能够让这个游戏至少玩过一次没问题。出于某种原因,有时候猜测数字的正确答案是+1超出范围(例如,我做最多3,猜测5,正确答案最终以某种方式为4)。我也被允许比我想要的更多猜测。这不是我的首要任务,我稍后会解决这个问题,但我想帮助解决这个问题。我确定我只是在忽略一些事情。
我已经付出了一些努力来解决这个问题,我希望这个问题符合社区标准。我将在今天晚些时候自己完成这项工作,所以无论哪种方式我都会努力,但我会感激我能得到的任何帮助。谢谢。
答案 0 :(得分:1)
几个问题:
scan.nextInt()
与scan.nextLine();
进行任何通话,以处理并吞下此令牌System.in
你问你是否想在内在的while循环中再次玩,这是没有意义的。您需要在外部while循环中询问并获取此信息
最重要的是你需要学习如何调试。请查看此精彩参考:How to debug small programs