Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Dec 2009
    Posts
    173
    Thanks
    24
    Thanked 1 Time in 1 Post

    cant figure out nextLine()

    First ill show up some examples.

    Example 1:

    Code:
    Scanner e = new Scanner(System.in);
    e.nextInt();
    System.out.println("|"+ e.nextLine() +"|");
    inputs :
    10
    some phrase

    outputs :
    ||

    Example 2:

    Code:
    Scanner e = new Scanner(System.in);
    System.out.println("|"+ e.nextLine() +"|");
    inputs :
    some phrase

    outputs :
    |some phrase|


    i'd be glad if someone could help me on this. =)

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    Calling nextInt() will leave the linefeed on the input buffers. So when you call next line, it literally reads the next linefeed to process (where it typically results in an infinite input in the case of using a loop).
    Clear it first by calling nextLine() followed by the scan for the next input. An alternative which I personally use is to simply always request a nextLine and use try/catch for a cast to the type that I need.

  • Users who have thanked Fou-Lu for this post:

    sorlaker (07-07-2012)


  •  

    Posting Permissions

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