Is there a way to avoid while(true) if I need to evaluate the condition at the beginning?

leonardo :

I am learning Java and I am following a project to simulate a ski jump tournament. Basically they want me to replicate this action:

The tournament begins!

Write "jump" to jump; otherwise you quit: jump

Round 1

//do something

Write "jump" to jump; otherwise you quit: jump
(continues)

My question is solely on the way to loop this. I know I can do this by entering a while(true) loop, and break right away if the input by the user equals "quit". However, I've read in multiple places that this is a bad practice, and instead it should be: while(condition). If I were to do that, the loop wouldn't break until after it completes the first iteration. Say:

String command = "placeholder";
while (!command.equals("quit")) {
    System.out.println("Write \"jump\" to jump; otherwise you quit: ");
    command = input.nextLine();
    System.out.println("\nRound 1");

    }

If I do something like this, even if the command is "quit" it'd still do the first iteration of that loop. And if I add an if with a break, then there's no point to have the condition on the while loop. Is there a better way of doing this? should I just use a while(true) loop even though people say it's bad practice?

Goion :

Another thing you can try is to use switch statement. I don't know how many conditions you have so it might not be feasible. Here is the code.

Scanner input = new Scanner(System.in);
String command = "placeholder"; // magic at this line
while (!command.equals("quit")) {
    System.out.print("Write \"jump\" to jump; otherwise you quit: ");
    command = input.nextLine();
    switch (command) {
    case "jump":
        System.out.println("\nRound 1");
        break;
    case "quit":
        break;
    default:
        break;
    }
}

This does not print "Round 1".

Since you were restrict to if-statements. There is another thing you can try and that is using continue

From Javadoc

The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.

So right after you ask user input you either continue to next loop or remain in same. This can be done via an if statement. Here is the code.

Scanner input = new Scanner(System.in);
String command = "placeholder"; // magic at this line
while (!command.equals("quit")) {
    System.out.println("Write \"jump\" to jump; otherwise you quit: ");
    command = input.nextLine();
    if (command.equals("quit"))
        continue;
    System.out.println("\nRound 1");
}

It is kinda like break but instead of exiting the loop altogether it evaluates the condition.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=139157&siteId=1