我正在尝试开发一个简单的高低游戏,如果他们想再玩一下,在玩游戏后会询问用户。如果我删除外部while循环,内部循环的逻辑正是我想要它做的,但是我不确定如何用一个外部循环来包装内部循环,这将再次询问游戏问题,如果答案是肯定的话他们回到内循环。以下是我的代码。
import java.util.Scanner;
import java.util.Random;
public class HiLoGuess {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100)+1; // Generates a random number for the game.
int count = 0; // Placeholder for the guess counter.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
String newgame = "y";
while (newgame.equalsIgnoreCase("y"))
{
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{
System.out.println ("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0 )
{
System.out.println("Your guess is too low, guess again");
}
else if (guess > answer)
{
System.out.println ("Your guess is to high, guess again");
}
else if (guess == answer)
{
System.out.println ();
System.out.println ("You guessed correctly, you win!!!");
System.out.println ("It took you " + count + " guesses");
}
}
System.out.print();
System.out.println("Play another game: y or n?");
newgame = scan.nextLine();
}
}
}
答案 0 :(得分:0)
您需要将这些初始化放入外部循环中:
int guess = -1;
int answer = numb.nextInt(100)+1;
int count = 0;
否则他们保留上一场比赛的值,内圈不再被执行。
答案 1 :(得分:0)
你永远不会重置你的猜测,哨兵或回答变量
so(guess!= sentinel&amp;&amp; guess!= answer)在第一次玩游戏后总是评估为false,因此内部while循环在第一次游戏后永远不会执行
while (guess != sentinel && guess != answer) //this is false after the first game because you don't reset variables
{ ...}
OP评论更新: 让你的代码做你想要的你需要在outter和inner while循环之间添加重置像这样
while (newgame.equalsIgnoreCase("y"))
{
guess = -1;
answer = numb.nextInt(100)+1;
count = 0;
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{ ...}
}
答案 2 :(得分:-1)
替换newgame = scan.nextLine();通过这个:newgame = scan.next();
您需要在while循环中初始化变量,以便将标志重置为false并随机生成新结果以进行猜测。
Return