Greetings! I'm doing some simple lab work, and have a slight problem I can't quite figure out (altho' it might be a lack of sleep ). Here's my simple code:
The method I need to use from the Utils file is as follows:
What I'm trying to do is make sure they input something, and I believe my instructor's code should return a null if nothing is input. However, even if I don't do anything but hit "enter", I'm not getting the s.o.p I expect from my while. I was able to make the code work using while (s.length() == 0) and get the results I'm looking for, but I'm curious why the above code doesn't work as expected. Any advice? Thanks, dav [ March 23, 2004: Message edited by: dav mccartney ]
No. The code will return a null only if some exception occurs. If the user hasn't entered anything, that method will return a empty String and not a null.
Joined: Jun 09, 2003
In his class Posfix he's testing for a null :- "and I believe my instructor's code should return a null if nothing is input" I'm trying to show him, in the various if statements (null being first), it is an empty string he should be testing for.
This is a common misconception with System.in and BufferedReaders. Looking at the API for BufferedReader, you notice it says it returns null if the end of the stream is reached. So, most assume that reading from System.in will return null if the user presses enter without entering anything. The problem is that System.in NEVER reaches the end of the stream. It's always open so readLine() on System.in will never return null. As has already been pointed out, your instructors method will only return null if it encounters an error. As was also previously mentioned, if you want to check for the user hitting enter without typing anything else, check to see if the length of the returned string is 0. Technically, the user DID type something, either a LF or a CR/LF combination depending on the OS. readLine() strips those characters and returns what is left - but a string with no characters is not the same as a null. Hope this helps,
Tom Blough<br /> <blockquote><font size="1" face="Verdana, Arial">quote:</font><hr>Cum catapultae proscriptae erunt tum soli proscripti catapultas habebunt.<hr></blockquote>
subject: Getting input with instructor code isn't working as I would expect...