开发者

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:

  1. Use Object#equals() method.

    while (!cont.equals("n")) {
        // ...
    }
    
  2. Use the primitive char instead of String.

    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" ) ) {
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜