简体   繁体   中英

Guessing game in java using math.random

Hi I'm trying to use Math.random to generate a random number between 0 and 100, then ask a user to enter a number between 0 and 100, or -1 to quit. If the number is out of bounds (and not -1), ask the user to enter a new number. If the user doesn't guess the number correctly, tell the user if the random number is higher or lower than the guessed number. Let the user make guesses until they enter the correct number or they enter -1. If they guess the correct number, tell the user how many tries it took and start the game again. It will Continue to play until the user quits.

I'm stuck on how to only get the user to enter 0-100 and on how to exit the loop by entering -1

This is what I have so far, any help would be appreciated !

import java.util.Scanner;

public class QuestionOne
{
  public static void main(String args[])
  {
   Scanner keyboard = new Scanner(System.in);

   int a = 1 + (int) (Math.random() * 99);
   int guess;

   System.out.println("Guess a number between 0-100");


   while(guess != a){
   guess = keyboard.nextInt();
   if (guess > a)
   {  
     System.out.println("The number is lower!");

   }
   else if (guess < a) 
   {
    System.out.println("higher!");

   }
   else 
   {
     System.out.println("Congratulations.You guessed the number with" + count + "tries!");
   }
   }
  }
}

For a start, your call to keyboard.nextInt() (and its corresponding println of "Guess a number between 0-100") should be within your while loop.

Then you should consider changing your while loop to

while (true) {
    // read input from user
    if (guess < value) { // tell user their guess is too low
    } else if (guess > value) { // tell user their guess is too high
    } else { // tell user congrats, and call break to exit the while loop }
    }
}

Once you get that right, you can work on the nice-to-haves, like checking numbers guessed are within bounds, keeping track of how many guesses they've done, etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM