Re: How to detect blank input using Scanner?
- From: Knute Johnson <nospam@xxxxxxxxxxxxxxxxxxxxxxx>
- Date: Sun, 28 Jan 2007 13:40:56 -0800
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/
.
- Follow-Ups:
- Re: How to detect blank input using Scanner?
- From: Taria
- Re: How to detect blank input using Scanner?
- References:
- How to detect blank input using Scanner?
- From: Taria
- How to detect blank input using Scanner?
- Prev by Date: Re: How do you execute a JAR file?
- Next by Date: Re: How do you execute a JAR file?
- Previous by thread: How to detect blank input using Scanner?
- Next by thread: Re: How to detect blank input using Scanner?
- Index(es):