Monday 26 December 2016

java.util.scanner - Java scanner test for empty line



I'm using Scanner to read 3 lines of input, the first two are strings and the last one is int.
I'm having an issue when the first line is empty and I don't know how to get around it. I have to do this:



String operation = sc.nextLine();
String line = sc.nextLine();

int index = sc.nextInt();
encrypt(operation,line,index);


But when the first line is empty I get an error message.
I tried the following to force a loop until I get a non empty next line but it does not work either:



        while(sc.nextLine().isEmpty){
operation = sc.nextLine();}



Anybody has a hint please ?


Answer



A loop should work, though you must actually call the isEmpty method and scan only once per iteration



String operation = "";
do {
operation = sc.nextLine();
} while(operation.isEmpty());



You could also use sc.hasNextLine() to check if anything is there


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...