Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting input with instructor code isn't working as I would expect...

 
dav mccartney
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Test with something like this
 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Tom Blough
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic