我的代码有问题。出于某种原因,每次我运行代码时,“ if(guess <1 || guess> 10) System.out.println(“您的猜测必须在1到10”之间);“语句被计为猜测尝试。目标是如果玩家的猜测超出1-10范围,则不具有尝试计数。我尝试过休息;但是我做错了吗,如果用户超出范围(没有计入尝试),有人知道如何打破循环并返回到猜测吗?
谢谢
json_encode
答案 0 :(得分:0)
您需要在方法“ askForGuess()”中输入内容,并且增量也会在其中完成,例如以下内容
public class GuessTheNumber
{
private Scanner input = new Scanner(System.in);
private SecureRandom randomNumbers = new SecureRandom();
private int numberOfGuesses;
public void play() {
numberOfGuesses = 0;
int magicNumber = 1 + randomNumbers.nextInt(10);
int guess = 0;
while(guess != magicNumber){
// Some kind of loop, maybe while
guess = askForGuess();
// is theGuess equal to magicNumber or is it
if (guess == magicNumber)
System.out.println("Yes, the number is " + magicNumber);
else if (guess > magicNumber)
System.out.println("Your guess is too high");
else if (guess < magicNumber)
System.out.println("Your guess is too low");
System.out.println ("Number of times guessed: " + numberOfGuesses );
}
}
private int askForGuess( )
{
int guess = 0;
// prompt for a guess
System.out.println("Enter a number:");
guess = input.nextInt();
if (guess <1 || guess >10 )
System.out.println ("Your guess needs to be between 1 and 10");
else
numberOfGuesses++;
return guess;
}
}