我如何退出switch语句并返回While循环?

问题描述 投票:1回答:1

因此,我尝试的是,在我通过一项搜索获得足够的结果之后,转到另一项搜索。换句话说,我想退出switch语句并返回到while循环。我该怎么办?

我将此作为代码:

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!");

        }

    }
}
java loops while-loop switch-statement exit
1个回答
0
投票

一旦进入循环,您就永远不会更新input,因此您可以无限期地返回while循环。有几种方法可以做到,一种是do while循环。喜欢,

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"));

另一个将是您使用quit中断的无限循环。喜欢,

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:是which而不是witch

© www.soinside.com 2019 - 2024. All rights reserved.