Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java Scanner issues

  1. Nov 5, 2009 #1


    User Avatar

    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,

    Here is a code chunk at the moment:

    Code (Text):
    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;
  2. jcsd
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted
Similar Discussions: Java Scanner issues
  1. Scanner Help? (java) (Replies: 0)

  2. Java array issue (Replies: 7)

  3. Fingerprint Scanner (Replies: 3)

  4. Java Tokenizer Issues (Replies: 1)