Thursday, February 09, 2006

JAVA Scanner's nextLine()

This is a simple concept, but some people may not be familiar with it since it's not used that often. When using JAVA's Scanner class to do standard input/output from the keyboard, make sure you use the nextLine() method of Scanner instead of next(), when you want the program to do something when the user just hits enter at the console without typing anything.

Of course, this is only true if you're checking that the input is blank. If you use
next(), you have to match the input string with the newline character. For example, to throw an exception (or do whatever you want), when the user hits enter without entering any input:

Scanner stdin = new Scanner(System.in);

String inputString = stdin.nextLine();
if(inputString.equals(""))
{
//do whatever, mabye throw an exception
//or display a message
}

That little code snippet will work, doing whatever is in the brackets of the if statement when the user hits enter without typing anything. You can also use inputString == "", inputString.charAt(0) == '',
inputString.length == 0, etc to test the content of the string.

This was a real problem for me, I spent 20 extra minutes on a lab because of it. If you want to implement the input this way, be sure to use nextLine(), not next().
Enjoy, and stay tuned for more programming tips!


No comments: