| Thread Closed |
Java Scanner issues |
Share Thread | Thread Tools |
| Nov5-09, 11:46 AM | #1 |
|
|
Java Scanner issues
I am having some trouble with the Java Scanner to read input from the keyboard.
I am trying to keep my input cleaned up and secure, so I am checking for the right type and value, and clearing the input buffer if it isn't. I also restart the prompt loop if it isn't right, so they can try again. I am using the .nextLine() method to clear the input buffer. The problem that I am seeing is that I sometimes don't get a repeated prompt until I enter in a second input. Things seem to work fine without the nextLine() calls, but then I always feel like I am leaving a dangling possible problem. I was also trying to use combinations of while(!talkToMe.hasNextInt()) loops to try and get away from my Flag system shown below, but it didn't quite seem to work so I stuck with the flags. I have read through the Java API documentation but that didn't seem to help, and I have done other searches for explanations of the Scanner object. It just feels like I am missing some key element of how the Scanner class is working. Is it an interrupt driven thing? A sit-and-wait-for-the-input thing? These questions might be the root of it; perhaps by executing .nextLine() it is actually waiting instead of going to the next statement. Thanks for the help, JJC Here is a code chunk at the moment: Code:
private int createPin1 (String prompt) {
int pin1=-1;
boolean flag = false;
while (!flag){
talkToMe.nextLine(); //not sure if this line is going to mess things up.
do {
System.out.print(""+ prompt); //Asking for pin number.
}while (!talkToMe.hasNextInt());
pin1 = talkToMe.nextInt();
talkToMe.nextLine(); //not sure if this might mess things up again.
if (pin1 <= 0){
System.out.println("Try again; please enter an integer > 0.");
// System.out.println(""+ prompt);
}else flag = true;
}
return pin1;
}
|
| Thread Closed |
| Thread Tools | |
Similar Threads for: Java Scanner issues
|
||||
| Thread | Forum | Replies | ||
| Using Scanner in Java to await user hitting return key | Programming & Comp Sci | 1 | ||
| Java Scanner | Programming & Comp Sci | 2 | ||
| Scanner Help? (java) | Engineering, Comp Sci, & Technology Homework | 0 | ||
| put my hand on scanner | Biology | 13 | ||