Tuesday, 22 December 2015

Java Scanner class confusion

If you have used Java's Scanner class, yopu may have come across an odd behaviour as you use the same Scanner object to input numbers and Strings.
I recently found the best explanation for this behaviour (it's not a bug), which you may find and here here at Daniweb. The best replies are from and

The reason it gives you trouble is because when the user enters an integer then hits enter, two things have just been entered - the integer and a "newline" which is \n. The method you are calling, "nextInt", only reads in the integer, which leaves the newline in the input stream. But calling nextLine() does read in newlines, which is why you had to call nextLine() before your code would work. You could have also called next(), which would also have read in the newline. (BestJewSinceJC)

Just change the delimiter.

Scanner in = new Scanner(System.in);

Hope you find these useful.

No comments:

Memory and Storage Devices

Videos related to the Computer Architecture topic (memory and storage devices) https://www.youtube.com/watch?v=NtPc0jI21i0 How a Hard Disk...