Order of while loops in Java

Viewed 86

I wrote a program that looks something like this

System.out.println ("What would you like to do?");
String task = sc.nextLine();

Then based on the input, I have a bunch of while loops for each input

while (task.equals("example")) {

//do something

System.out.println ("What would you like to do now?");
task = sc.nextLine();
}

while (task.equals("example 2")) {

//do something

System.out.println ("What would you like to do now?");
task = sc.nextLine();
}

etc. At the end of each loop the user can input what they want to do next, and depending on what they say, the corresponding while loop should execute.

But I can't get a while loop that's above another one to execute. So if I'm in the "example" loop, I can execute the "example 2" loop afterwards because it is below it. But if I'm in the "example 2" loop, I can't execute the "example" loop which is above it. Is there any way around this?

2 Answers

Yes, the way you could go around it is to pack it all up in a single loop and then a simple if statement should do the trick :)

String task;
while(true) {                  //or !task.equals("exit")
    System.out.println("What would you like to do now?");
    task = sc.nextLine();
    if(task.equals("example") {
        //do something
    }else if(task.equals("example 2") {
        //do something
    }
    ...
    }else { break; }          // You can also use this to break out of your loop
}

oooh, a loop means loop, you can do a lot of thing in it. so you can do it with just one loop:

    public static void main(String[] args) {
        String task;
        Scanner sc = new Scanner(System.in);
        do {
            System.out.println("What would you like to do?");
            task = sc.nextLine();
            switch (task) {
                case "example":
                    System.out.println("example 1");
                    break;
                case "example 2":
                    System.out.println("example 2");
                    break;
                default:
                    break;
            }
        } while (!"exit".equals(task));
        System.out.println("task exit");
    }
Related