Tim Driven Development | Test until the fear goes away
Tim Driven Development | Test until the fear goes away
Tim Cooke wrote:Actually, I'm posting nonsense again.
If you input nothing, does input.nextLine() return null or an empty String?
Tim Driven Development | Test until the fear goes away
Tim Driven Development | Test until the fear goes away
Tim Cooke wrote:Well now, (name != "") is another issue entirely. One where the advice is to AvoidTheEqualityOperator <-- read this link
Tim Driven Development | Test until the fear goes away
Tim Cooke wrote:Seeing as though Liutaurus has spoiled the learning and discovery fun by giving you the answer
Liutauras Vilda wrote:
Tim Cooke wrote:Seeing as though Liutaurus has spoiled the learning and discovery fun by giving you the answer
Well, you're right about that, my fault, sorry about that.
Tim Cooke wrote:That's because String is not a primitive type. it's a descendant of Object.
Seeing as though Liutaurus has spoiled the learning and discovery fun by giving you the answer, I shall modify it slightly and give you my top tip for handling null Strings when comparing.
Let's say in your code, name could be null. To check for a non empty String you'd need to do something like this:
However, you can simplify this by reversing the .equals(), like so:
If name is null, then the condition is false. A NullPointerException is not possible here.
Tim Driven Development | Test until the fear goes away
Liutauras Vilda wrote:sorry about that.
Tim Driven Development | Test until the fear goes away
Tim Cooke wrote:
This says: "do while name not equal to empty string". Which is what you want right?
or while( name.length() > 0 )Adam Chalkley wrote:
Tim Cooke wrote:
This says: "do while name not equal to empty string". Which is what you want right?
indeed just the order confused me haha
Campbell Ritchie wrote:while(input.trim().isEmpty());
… which will catch cases where you only enter whitespace. In that case the null check might become necessary again.
Campbell Ritchie wrote:If you push ctrl‑Z you might have null returned from nextLine. I have never tried it, but I shall and shall report back.
So you can never get null however hard you try because you get a different Exception if the stream for input is emptyjava Username
enter your name
[enter]
hi
enter your name
[enter]
hi
enter your name
[enter]
hi
enter your name[ctrl‑D]
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Username.main(Username.java:13)