Reputation: 71
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
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
Reputation: 2109
You can edit your code with the following:
while (!login().equals("OK")) {
System.out.println("ERROR, Try again...!");
}
Upvotes: 1
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