Reputation: 41
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?
Upvotes: 4
Views: 60525
Reputation: 3415
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.
Upvotes: 5
Reputation: 1174
The exclamation point !
represents negation or compliment. while(!"jack".equals(name)){ }
Upvotes: 12
Reputation: 35
Put the "!" in from of jack. That will solve if I understand the question correctly.
Upvotes: 3