Results 1 to 7 of 7
Thread: Scanner problem.
- 04-07-2011, 06:40 AM #1
Member
- Join Date
- May 2010
- Posts
- 34
- Rep Power
- 0
Scanner problem.
Hello, I am working on a terminal based game and have a problem with the scanner.
The below code is part of the "players turn". The first time the method is called for the game, it prints once and works perfectly. Then during the second calling & onwards, it prints the "Message..." and "type a command:..." lines twice before it offers me to input a string into the terminal.
I have been trying to fix this for hours... Im working in netbeans but have also taken it to bluej and used that debugged to trace, it simply skips over it the first time (after the second time its called).Java Code:if(!notComputerTurn) { System.out.println("Message..."); System.out.println("type a command: play, move, exit"); String keyWord = scan.nextLine(); if(keyWord.contains("play")) { int number scan.nextInt(); ... } ... }
Whats wrong?
Thank you.Last edited by keo; 04-07-2011 at 06:49 AM.
- 04-07-2011, 06:45 AM #2
Do you call nextInt or nextDouble anywhere in the code you omitted?
- 04-07-2011, 06:48 AM #3
Member
- Join Date
- May 2010
- Posts
- 34
- Rep Power
- 0
Oops, I wrote my code wrong, but yes, there is a nextInt is that the problem? Thanks for helping.
Wrong:
Correct:Java Code:if(keyWord.contains("play")) { String keyWord = scan.nextLine(); ... }
Java Code:if(keyWord.contains("play")) { int number scan.nextInt(); ... } ...
- 04-07-2011, 06:54 AM #4
Yes nextInt is notorious for causing headaches. If user enter 9[enter] the nextInt method reads the 9 but not the enter. The next time you call nextLine it reads the empty String between the 9 and enter and carries on as if user had entered something. Solution: after the call to nextInt make a call to nextLine and throw it away.
- 04-07-2011, 07:10 AM #5
Member
- Join Date
- May 2010
- Posts
- 34
- Rep Power
- 0
Thank you so much Junky! :):):):):)
I have spent so many hours just trying to fix this bug, and I would have never of fixed it without asking :rolleyes:.
- 04-07-2011, 07:46 AM #6
Learn to search the net intelligently. Google gives a truckload of useful results when searching "nextint nextline problem"I would have never of fixed it without asking
db
- 04-07-2011, 08:30 AM #7
Member
- Join Date
- May 2010
- Posts
- 34
- Rep Power
- 0
Similar Threads
-
Scanner Class Problem
By jgg in forum New To JavaReplies: 1Last Post: 02-10-2011, 01:07 PM -
Scanner problem
By mkay in forum New To JavaReplies: 2Last Post: 10-28-2010, 12:09 AM -
Problem with scanner
By JavaJ in forum New To JavaReplies: 6Last Post: 03-16-2010, 08:51 PM -
Problem with scanner
By Kangaroo128 in forum New To JavaReplies: 11Last Post: 09-01-2009, 08:07 AM -
Problem with scanner in loop
By grifan526 in forum New To JavaReplies: 2Last Post: 07-21-2009, 12:06 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks