Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    help with creating a guessing game

    Hello. I am working on a homework assignment for my intro java class. The program should generate a random number from 1 to 20, and prompt the user for a guess. If the user guesses wrong, the program prompts the user again for the same number (no new random number). The program should keep asking the user until he/she gets it right.

    Once the user guesses the right number, the program should display "You won! The number of guesses was ___". Guesses outside the range of 1-20 do not count.

    I keep trying to make this program work but i am struggling hard. for starters, is this how you generate a random number?

    [CODE]Random rGen = new Random();

    rNum = rGen.nextInt(20) + 1;[CODE]

  • #2
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    my professor gave us this algorithm sheet to help us out.

     Declare all needed variables
    Int user's guess
    Int random number
    Int count the valid attempts
    Scanner class object
    Random class object
     Create a random number and assign it to the variable
     Begin loop(while user's guess !=random number)
    Prompt for the user's guess
    Compare user's guess to the random number
    If (user's guess equals random number)
    Output “You won!”
    Else
    Output “Try again.”

    but i dont understand why you would begin the loop before prompting for the user's guess. should i follow this? or am i just not getting it?

  • #3
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    For your first question, Random can be used to get an inclusive to exclusive random number. So that would give between 1 and 20.
    For your second question, its for convenience. If you don't do it, then you need to write the code to handle the input twice, the first time to determine if the loop should be entered, and then again to take input if the answer is incorrect. Putting it within the loop prevents needing two prompts.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •