Sunday, September 18, 2011

next() and nextLine()

When I was a newbie programmer, I used to be frustrated a lot every time I used the Scanner class. At the time, it seemed like it behaved erratically and no matter how much debugging I did, it was always wrong.

The mistake I was making was that I failed to realize that whenever I used a .next call, like nextInt or nextDouble, the Scanner would stay on the same line. If then, I wanted to scan a new input that was on a different line, the Scanner will appear to skip it. What happens is that the Scanner is actually scanning the invisible newline character!

So, whenever you want to Scan numbers with a .next() call, make sure you add an empty .nextLine() at the end so that the Scanner moves to the correct position.




import java.util.Scanner;

class myClass {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
double grade=0;
String name=null;
System.out.print("Please enter the grade: ");
grade = scn.nextDouble(); //Could also be scn.next(), scn.nextInt(), and so on
//Add an empy .nextLine() to skip the invisible newline character
scn.nextLine(); //Try commenting this line out with '//' to see what happens
System.out.print("Please enter name: ");
name = scn.nextLine();
System.out.println("Name: "+name+", grade: "+grade);
}
}


Sample run without the empty scn.nextLine:


Please enter the grade: 76
Please enter name: Name: , grade: 76.0


Sample run with the empty scn.nextLine:


Please enter the grade: 100
Please enter name: Rommel
Name: Rommel, grade: 100.0



From: http://rommelrico.com/java-scanner-not-working-difference-between-next-and-nextline/

1 comment:

  1. Conclusion:
    All next...() except nextLine()
    will stay on the same line that without consume the newline character!

    ReplyDelete