简体   繁体   中英

How can i exit switch statement and get back to While loop?

So what I am trying is, after I get enough results by one of the searches to go to the other one. In other words I want to exit the switch statement and get back to while loop. How can I do this?

I have this as a code:

public static void main(String[] args) throws FileNotFoundException {


    String input = "";
    Scanner scan = new Scanner(System.in);
    System.out.println("Hello, input witch method you shall use(name, amount or date): ");
    input = scan.next();

    Warehouse storage = new Warehouse();
    //todo while loop kad amzinai veiktu. Ar to reikia ?
    while (!input.equals("quit")) {
        switch (input) {
            case "name":
                storage.searchByName();
                break;
            case "amount":
                storage.searchByAmount();
                break;
            default:
                System.out.println("Wrong input!");

        }

    }
}

Once you enter your loop you never update input and so you do go back to your while loop (infinitely). There are a few ways you could do that, one is a do while loop. Like,

String helloMsg = "Hello, input which method you shall use(name, amount or date): ";
Scanner scan = new Scanner(System.in);
Warehouse storage = new Warehouse();
String input;
do {
    System.out.println(helloMsg);
    input = scan.next();
    switch (input) {
    case "name":
        storage.searchByName();
        break;
    case "amount":
        storage.searchByAmount();
        break;
    default:
        System.out.println("Wrong input!");
    }
} while (!input.equals("quit"));

Another would be an infinite loop that you use quit to break from. Like,

String helloMsg = "Hello, input which method you shall use(name, amount or date): ";
Scanner scan = new Scanner(System.in);
Warehouse storage = new Warehouse();
loop: while (true) {
    System.out.println(helloMsg);
    String input = scan.next();
    switch (input) {
    case "name":
        storage.searchByName();
        break;
    case "amount":
        storage.searchByAmount();
        break;
    case "quit":
        break loop;
    default:
        System.out.println("Wrong input!");
    }
}

Note : It's which not witch .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM