Reputation: 49
I have this loop:
String cont = "";
while ( cont != "n" ) {
// Loop stuff
System.out.print("another item (y/n)?");
cont = input.next();
}
However, when I type "n" to stop the loop, it just keeps running. Whats wrong?
Upvotes: 0
Views: 2177
Reputation: 1108642
You're comparing objects instead of primitives. A String
is an object, the ==
and !=
doesn't compare objects by "internal value", but by reference.
You have 2 options:
Use Object#equals()
method.
while (!cont.equals("n")) {
// ...
}
Use the primitive char
instead of String
.
char cont = 'y';
while (cont != 'n') {
// ...
cont = input.next().charAt(0);
}
Upvotes: 6
Reputation: 29619
Use the .equals method instead.
String cont = "";
do {
// Loop stuff
System.out.print("another item (y/n)?");
cont = input.next();
} while ( !"n".equals(cont) );
Upvotes: 0