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 cgeier and BestJewSinceJC
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.
No comments:
Post a Comment