3 Replies - 976 Views - Last Post: 03 October 2012 - 03:51 AM Rate Topic: -----

#1 Gisengryl  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 125
  • Joined: 08-September 12

Understanding nextLine().

Posted 02 October 2012 - 10:19 PM

import java.util.Scanner;
public class readstring1{
	public static void main (String args[]){
		Scanner sc = new Scanner(System.in);
		
		
		System.out.print("Enter number: ");
		int ax = sc.nextInt();
		
		System.out.print("Enter word: ");
		String wq = sc.nextLine();   

                System.out.println ("Number is "+ ax);
		System.out.println ("Word is " + wq);
		
	}
}




given the above code, the result will be :
Enter number: 111
Enter word: Number is 111
Word is


Is this because nextLine() skips the current line it is supposed to scan ( which is System.out.print("Enter word: "); ) and returns the skipped input ( which is only Enter word: ) ?

This is what I understand from the java documentation..

Using next() instead will give no problems. So what's the purpose of nextLine() ?

Thanks alot.

This post has been edited by Gisengryl: 02 October 2012 - 10:19 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Understanding nextLine().

#2 dimasalang  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 4
  • Joined: 02-October 12

Re: Understanding nextLine().

Posted 02 October 2012 - 10:45 PM

Hi there. Yes your understanding is correct. According to oracle's documentation

Quote

nextLine() Advances this scanner past the current line and returns the input that was skipped.


nextLine() can be used when you're reading Strings from a text file with multiple line of texts.
Was This Post Helpful? 1
  • +
  • -

#3 CasiOo  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 1275
  • View blog
  • Posts: 2,840
  • Joined: 05-April 11

Re: Understanding nextLine().

Posted 02 October 2012 - 10:48 PM

This line could be an example of what the stream buffer could look like after inputs
10\rMyWord\r

nextInt will read the number '10' but it will leave behind \rMyWord
nextLine will read until the next whitespace which is \r. MyWord has still not been read, and this call to nextLine returns an empty string.

The 2nd call to nextLine() will return MyWord and eat the \r :)
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: Understanding nextLine().

Posted 03 October 2012 - 03:51 AM

It was designed so that:

int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();

can be enter by the user as:
1 2 3
or
1
2
3
or
1 2
3
or
1
2 3

nextInt(), next(), nextFloat(), nextBoolean(),... will skip linefeed to reach what they are looking for
nextLine() simply read the nextLne() empty or not
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1