有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

添加“再次播放?”Java中我的随机数猜测游戏的功能

我一直被困在这个问题上,当用户被要求继续时,我似乎无法再次循环。do while循环是否更适合这种类型的“再次播放”功能?任何帮助都将不胜感激,谢谢

import java.util.Scanner;
import java.util.Random;

public class HiLo

{
   public static void main( String[] args )  
{
  boolean again = true;

  while (again == true)
  {
  int MAX = 100;
  int MIN = 1;
  int guessCounter = 1;
  int outOfRangeCounter = 0;
  int userGuess = 0;
  Random rand = new Random();
  int computerGuess = rand.nextInt(MAX) + MIN;
  System.out.printf("Welcome to the game of Hi-Lo...\n\n\n");
  System.out.printf("I have chosen a random number for you to guess.\n\n");
  Scanner keyboard = new Scanner(System.in);
  String repeatAgain;


  while (userGuess != computerGuess)
  {   
     System.out.printf("Guess %d: Enter a number between %d and %d: ",guessCounter,MIN,MAX);
     userGuess = keyboard.nextInt();
     if (userGuess == computerGuess)
     {
        System.out.printf("%d is correct\n\n",userGuess);
     }
     else if (userGuess > MAX || userGuess < MIN)
     {
        System.out.printf("%d is not between %d and %d\n\n",userGuess,MIN,MAX);
        outOfRangeCounter++;
     }
     else if (userGuess > computerGuess)
     {
        System.out.printf("%d is too high\n\n",userGuess);
        MAX = userGuess - 1;
        guessCounter++;
     } 
     else if (userGuess < computerGuess)
     {
        System.out.printf("%d is too low\n\n",userGuess);
        MIN = userGuess + 1;
        guessCounter++;   
     }       
  }
  System.out.printf("It took you %d valid guesses to find the number.\n",guessCounter);
  System.out.printf("You had %d out of range guesses.\n\n",outOfRangeCounter);
  System.out.printf("Do you want to play again? (Y or N): ");
  repeatAgain = keyboard.nextLine();
     if (repeatAgain.equalsIgnoreCase("Y"))
        {
           again = true;
        }
     else
        {
           again = false;
        }
   }         
 } 
}

共 (2) 个答案

  1. # 1 楼答案

    nextLine()跳过一行并返回跳过的行

            //change
            //repeatAgain = keyboard.nextLine();
            //to
            repeatAgain = keyboard.next();
    
  2. # 2 楼答案

    repeatAgain = keyboard.next();改变repeatAgain = keyboard.nextLine();,它应该是固定的