猿问

循环内的随机数生成器

尝试在控制猜数游戏的 while 循环中创建一个随机数生成器。问题是“太高”和“太低”提示会说一个数字(例如:35)太低,但随后会说嵌套输入数字(例如:36)太高。然后,当我在嵌套的 while 循环中移动调用随机函数时,它每次都会生成相同的随机数。


我尝试将对随机函数的调用移动到我最内层的循环,但随后它生成了相同的随机数。当前,它在外部 while 循环中,但随后出现高/低问题


import java.util.Scanner;

import java.util.Random;

public class numberGuessingGame

{

     public static void main (String[] args) 

    {

        int randomNumber, userNumber = 0, guesses = 0, correct;

        final int MAX = 100;

        char playAgain, playGame = 'y'; 



        //ask user if they wish to play   

        System.out.println("Would you like to play the Number          Guessing Game? y / n");


        Scanner scan = new Scanner (System.in);

        playGame = scan.next().charAt(0); 

        Random generator = new Random();


        //while loop to continue to exacute game as long as user enters 'y'

        while (playGame == 'y'){

            if (playGame != 'y') 

               break;


            randomNumber = generator.nextInt(MAX) + 1;

            //flag

            correct = 0;


           //loop to control the round

           while (correct == 0) {


                //get user number


                System.out.println("Please pick a number between 1 and 100.");

                userNumber = scan.nextInt();


               //high and low sugguestion

                if (userNumber > randomNumber)

                    System.out.println("Number is too high, try     something lower.");


                if (userNumber < randomNumber)

                    System.out.println("Number is too low, try something higher.");


                if (userNumber == randomNumber){ 

                 System.out.println("That number is correct!");

                    System.out.println("Would you like to play again? y/n");

                    playGame = scan.next().charAt(0);

                }


                guesses++;

                System.out.println("You have guessed " + guesses + " times!");

           }  


    }



收到一只叮咚
浏览 114回答 2
2回答

忽然笑

我想建议您可能会考虑的一些更改:使用booleanforcorrect而不是int在: 它是多余的之后立即删除您的if声明whiledo-while当循环必须至少执行一次时使用使用Integer.compareTo而不是单独比较

qq_花开花谢_0

你的内部循环不会终止,这就是为什么你有相同的 randomNumber,更改correct=0值以终止内部 while 循环if (userNumber == randomNumber){&nbsp;&nbsp;System.out.println("That number is correct!");&nbsp;System.out.println("Would you like to play again? y/n");&nbsp;playGame = scan.next().charAt(0);&nbsp;correct=1; //Just to remove correct=0 value}
随时随地看视频慕课网APP

相关分类

Java
我要回答