How to check for a single character and break a loop
I have this loop:
String cont = "";
while ( cont != "n" ) {
// Loop stuff
System.out.print("another item (y/n)?"开发者_JS百科);
cont = input.next();
}
However, when I type "n" to stop the loop, it just keeps running. Whats wrong?
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 ofString
.char cont = 'y'; while (cont != 'n') { // ... cont = input.next().charAt(0); }
You need to use equals()
:
while (!cont.equals("n")) {
Use the .equals method instead.
String cont = "";
do {
// Loop stuff
System.out.print("another item (y/n)?");
cont = input.next();
} while ( !"n".equals(cont) );
while ( !"n".equalsIgnoreCase(cont) )
Try this:
while ( !cont.equals( "n" ) ) {
精彩评论