DIFFERENCE BETWEEN next() AND nextLine()
This post eradicates the confusion between next() and nextLine() and gives you a clear idea of how they work.
next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
COMMON PROBLEMS WITH next() :
Consider the example,
import java.util.Scanner;
public class temp
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter string for c");
String c=sc.next();
System.out.println("c is "+c);
System.out.println("enter string for d");
String d=sc.next();
System.out.println("d is "+d);
}
}
OUTPUT: HOW IT WORKS!
enter string for c
abc def abc |def //cursor stays after c
c is abc
enter string for d
d is def abc def| //cursor stays after f
Look at the output keenly. When the input for c is given as abc def, it will not read the entire input abc def. next() reads only abc and places the cursor after the alphabet c. Now, when value for d is got using next(), it will not get new value. Rather, it takes the value after the current cursor position(since the cursor is after c, def is assigned to d and the cursor stays after f).
Now, when
String c=sc.next() in the above program is replaced as
String c=sc.nextLine(), the output will be
OUTPUT: HOW IT WORKS!
enter string for c
ABC DEF ABC DEF
c is ABC DEF | //cursor moves to next line
enter string for d
GHI ABC DEF
d is GHI GHI| //cursor stays after I
Since nextLine() is used for reading input for c, the entire line is read and hence ABC DEF is stored in c and the cursor is placed in the next line. Now when d is read using next() or nextLine(), the cursor will be in the next line and hence the input for d is read and is placed in d (here d gets the input GHI).
So whenever next() is used, make sure nextLine() used to place the cursor in the next line. Hence the above program is also written as,
String c=sc.next();
sc.nextLine();
String d=sc.next();
Thanks for reading my blog... :-) Comment about my blog. Stay tuned for my next post....