Re: How to detect blank input using Scanner?



Taria wrote:
I'm still a newbie in Java and I've searched the web for an answer but have not been able to find any.

All I want is to do this:

- Ask user for file name to read
- if input is blank
assign a defaulted name
else
use the name the user gives.

As simple as this seems, I'm having trouble detecting blank input if the user just hits <enter>.

My code:
...
Scanner input = new Scanner(System.ini);

// input.nextLine allows a carriage return
// input.next does not

String fileNameR = input.nextLine();
if (fileNameR == null) {
fileNameR = "grades.dat";
}

As long as I enter a word, this code works fine but if I hit return, the 'if' statement is never true thus never executed. I've also tried fileNameR == "\n" and fileNameR = "". All three conditions don't work.

I've tried using charAt but my results become an exception because this is an Index out of Bounds error.

(alternative charAt code I tried)
ch = fileNameR.charAt(0);
if (ch == '\n') {
... (code here)
}

Any help is appreciated.
Marion


We can't tell what you are doing without the code. A small, compilable test program is always helpful especially if it doesn't do what you want.

Remember to compare Strings use .equals() not ==.

--

Knute Johnson
email s/nospam/knute/
.