I'm trying to write a little block of code in Java with a do-while loop that asks the user's name. If it isn't the name the code is looking for, then it just repeats itself. For example,
Scanner scan = new Scanner();
do {
System.out.println("whats your name?");
String name = scan.nextLine();
} while ("jack".equals(name)); ////// <<<<
It's where I marked with <<<<
that I don't know what to do. I need something like !=
, but that does not work with strings.
So what can I put here?
The exclamation point !
represents negation or compliment. while(!"jack".equals(name)){ }
The boolean not ! operator is the cleanest way. Of course you could also say
if ("jack".equals(name) == false) { ... }
or you could say
if ("jack".equals(name) != true) { ... }
Beware if calling .equals()
on an object that could be null
or you'll get a NullPointerException
. In that case, something like...
if !((myVar == yourVar) || ((yourVar != null) && yourVar.equals(myVar))) { ... }
... would guard against an NullPointerException
and be true if they're no equal, including them both not being null
. Quite a brain-twister huh? I think that logic is sound, if ugly. That's why I write a StringUtil
class containing this logic in many projects!
That's why it's a better convention to invoke the .equals()
method on the string literal rather than the String you're testing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With