Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 07-07-2012, 04:21 AM   PM User | #1
sorlaker
Regular Coder

 
Join Date: Dec 2009
Posts: 167
Thanks: 23
Thanked 1 Time in 1 Post
sorlaker has a little shameless behaviour in the past
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. =)
sorlaker is offline   Reply With Quote
Old 07-07-2012, 04:37 AM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,752
Thanks: 4
Thanked 2,468 Times in 2,437 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
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.
Fou-Lu is offline   Reply With Quote
Users who have thanked Fou-Lu for this post:
sorlaker (07-07-2012)
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 12:40 PM.


Advertisement
Log in to turn off these ads.