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

    Help with simple Java problem?

    My technology teacher would like me to create a basic text game as a way to demonstrate user input.

    Here's the problem:

    I am using a Scanner to get user input and set that input to a varible:

    System.out.println("If you're ready, type any number to begin:");

    That sets A1 to whatever the user types in. If the user were to type in a number that's not a choice, nothing happens. If the user types in anything but a number, they get an error.

    What do I use to repeat the question if they type in something that is not an option?

  2. #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Saskatoon, Saskatchewan
    Thanked 2,662 Times in 2,631 Posts
    You capture the results as a string with nextLine instead, try/catch a cast to number with an Integer.parseInt, and then compare it to what is valid. Alternatively, you can use the Scanner's hasNext* methods to determine if the next token matches the proper type, and flush it when its invalid. That saves the try/catch with the cast.


Posting Permissions

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