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);
in.useDelimiter("\n");
(cgeier)

Hope you find these useful.

Optimise Windows 10/11

How to optimise your Windows setup Just in case you need it. If you want a safe and conservative approach, just disable the background apps ...