user7233170
user7233170

Reputation: 71

do while statments with if

consider the following code snippet:

           String msg = null;
            do {
                msg = login();
            } while (!msg.equals("OK"));

I want to display a message in the console when msg is different from"OK", for example: ERROR, Try again...!. I did this:

        String msg;
        do {
            msg = login();
            if(!msg.equals("OK")){
                System.out.println("ERROR, Try again...!");
            }
        } while (!msg.equals("OK"));

It works. I wonder if there is another elegant ways to do it.

Upvotes: 1

Views: 86

Answers (3)

shmosel
shmosel

Reputation: 50716

One option is to break the loop instead of using the condition clause. This lets you avoid the duplicated check:

String msg;
do {
    msg = login();
    if (msg.equals("OK")) {
        break;
    }
    System.out.println("ERROR, Try again...!");
} while (true);

Upvotes: 1

haMzox
haMzox

Reputation: 2109

You can edit your code with the following:

while (!login().equals("OK")) {
    System.out.println("ERROR, Try again...!");
}

Upvotes: 1

Bogdan Kobylynskyi
Bogdan Kobylynskyi

Reputation: 1220

String msg;
while (!(msg = login()).equals("OK")) {
    System.out.println("ERROR, Try again...!");
}

or even

while (!login().equals("OK")) {
    System.out.println("ERROR, Try again...!");
}

Upvotes: 6

Related Questions