Wednesday 6 June 2018

java.util.scanner - JAVA: Scanner doesn't read next line // returns empty string



So I am programming Snake at the moment and i have a Method to read an an integer value from the console.
When my Method throws a mistake - or atleast when i return to that method -
it doesn't read in a new line from input but just passes a a empty string.
Here is my code:




static int readInInt()
{
//We Read in the next line the user enters
String s = sc.nextLine();
//x returns -1 if mistake happens
int x = -1;

try
{

//Now we try to parse that int
x = Integer.parseInt(s);
x = Math.abs(x);
System.out.println("Setting the speed to " + (x*100) + "ms.");
}
catch(NumberFormatException ex)
{
//If we can't parse it we try to get the ints with a regex and then parse it
System.out.println("Du hast eine nummer eingetippt die das System nicht analysieren kann.");
System.out.println("Das System probiert jetzt die Nummer die du eingetippt hast über umwege zu Analysieren.");

s = s.replaceAll("[^-?0-9]+", "");
try
{
x = Integer.parseInt(s);
}
catch(Exception e)
{
//and if that doesnt work we just say Error!
System.out.println("Error Handling didn't work.\n"
+ "Please try again with just a simple number (e.g. 7)");

//Return an Error in form of -1
return -1;
}
x = Math.abs(x);
System.out.println("Setting the speed to " + (x*100) + "ms.");
}

return x;
}



I've declared "sc" as a static class variable static Scanner sc = new Scanner(System.in); at the beginnning of my programm.



Why does the scanner return an empty String? - without asking for user input -
And yes i am aware of the Method .readNextInt, but i find it easyer to handle exceptions like this.


Answer



Thanks @Seelenvirtuose who brought me to the right track of the solution!




I said, if in another place sc.nextInt() was used, you have a pending newline that was not consumed. The next sc.nextLine() only consumes this newline and does not give the priority to enter anything. The problem, therefore, is in another portion of your code! –





The solution was that in some parts of my code i was using sc.next() which only reads in the next string untill the whitespace (if i am not mistaken) and not sc.nextLine().
So I've changed all sc.next() to sc.nextLine() not it works just fine.



There are 2 other solutions that I've found while doing trail and error:
a) Write sc.reset() which does "Resetting a scanner discards all of its explicit state information[...]" bevor accesing the sc.nextLine()command or
b) Just create a new instance of the Scanner class.



Thanks again to Seelenvirtuose.


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...