Steven
Steven

Reputation: 49

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)?");
cont = input.next();
}

However, when I type "n" to stop the loop, it just keeps running. Whats wrong?

Upvotes: 0

Views: 2177

Answers (5)

Satya
Satya

Reputation: 4478

Try this:

while ( !cont.equals( "n" ) ) {

Upvotes: 0

Dead Programmer
Dead Programmer

Reputation: 12575

while ( !"n".equalsIgnoreCase(cont) )

Upvotes: 0

BalusC
BalusC

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:

  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);
    }
    

Upvotes: 6

krock
krock

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

Ted Hopp
Ted Hopp

Reputation: 234795

You need to use equals():

while (!cont.equals("n")) {

Upvotes: 1

Related Questions