简体   繁体   English

使用 math.random 在 java 中进行猜谜游戏

[英]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.嗨,我正在尝试使用 Math.random 生成 0 到 100 之间的随机数,然后要求用户输入 0 到 100 之间的数字,或者输入 -1 以退出。 If the number is out of bounds (and not -1), ask the user to enter a new number.如果数字超出范围(而不是 -1),请要求用户输入新数字。 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.让用户猜测直到他们输入正确的数字或​​输入 -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我被困在如何只让用户输入 0-100 以及如何通过输入 -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.首先,您对 keyboard.nextInt() 的调用(及其相应的“猜测 0-100 之间的数字”的 println )应该在您的 while 循环中。

Then you should consider changing your while loop to那么你应该考虑将你的 while 循环改为

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一旦你做对了,你就可以做一些不错的事情,比如检查猜测的数字是否在范围内,跟踪他们做了多少猜测等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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