Tuesday 7 January 2020

java.util.scanner - Last line of input not scanning in Java Scanner Class



I am trying to work on some stuff using the Scanner for input, but for some reason, the scanner is failing me.



I have the following code running, nothing complex:




while(scan.hasNextLine())
{
System.out.println(scan.nextLine());
}


Just as a test bed to make sure everything is being input correctly. If I copy my test material, say



5

4
3
2
1


The output omits the last line. I am pretty sure that it is because nextLine will only return a string if there is a string after it, even if it is empty, but I need it to work this way for the way I will eventually input the data to work. Does anyone know how I can fix this? My only guesses were to either use something other that scanner or to somehow append an empty string to the end of the input, but I wasn't sure how to do the second one, and I didn't think a different scanner-like thing would work. Thanks in advance!


Answer



Your last line MIGHT not have a "enter" char. So it does not treat it as the end of line. Try




> 5
> 4
> 3
> 2
> 1
>

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...