• Post Reply Bookmark Topic Watch Topic
  • New Topic

Getting user input the second time  RSS feed

 
Aron Silvester
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm working on creating a dice game and getting the users input is giving me a really hard time. I have the main game working but this part I'm stuck on. The problem is that it's not giving me the chance to enter the second input when I ask for the game.

//Create Scanner object
Scanner keys = new Scanner(System.in);

//Get chips
System.out.print("How much money would you like to change? ");
int chips = keys.nextInt();
System.out.println("You now have $" + chips + " in chips.");

//What game does the player want to play?
System.out.print("What game do you want to play? ");
String typeOfGame = keys.nextLine();

if (typeOfGame.matches("D|d|Dice|dice")) {
System.out.println("You picked dice.");
} else {
System.out.println("You did not pick dice.");
}

*****This is what I get when I run it
run:
How much money would you like to change? 50
You now have $50 in chips.
What game do you want to play? You did not pick dice.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Conrado Sanchez wrote:I'm working on creating a dice game and getting the users input is giving me a really hard time. I have the main game working but this part I'm stuck on. The problem is that it's not giving me the chance to enter the second input when I ask for the game.

The problem is that the nextLine() reads the newline that you probably entered when you entered your money amount. It's one of the 'gotchas' about Scanner, and just one reason I don't particularly like it.

There are two possible solutions:

1. Add a nextLine() after every non-String input you have.

2. Use nextLine() to get all your values, and then convert if needed, viz:I have to admit to a slight preference for this style because then I don't have to remember when I need to add an extra call.

You might want to have a look at the UserInput page, which goes into a bit more detail about the whole business of input.

HIH

Winston
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will find out Winston and I have different opinions about Scanner.
I think you should write yourself a utility class (maybe called KeyboardInputs) for using Scanners; you can then call KeyboardInputs.nextInt("Please enter a number:"); or similar. You can even arrange it so you never get any Exceptions. For next line you can try something like thismore details in this discussion, including a daft mistake of mine.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!