【问题标题】:How can i exit switch statement and get back to While loop?如何退出 switch 语句并返回到 While 循环?
【发布时间】:2020-04-13 20:42:30
【问题描述】:

所以我正在尝试的是,在我通过一项搜索获得足够的结果以转到另一项之后。换句话说,我想退出 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】:

    一旦你进入你的循环,你永远不会更新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!");
        }
    }
    

    注意:这是which 而不是witch

    【讨论】:

    • 哦,太好了,我没想到在交换机本身中使用“退出”!感谢您的更正!
    猜你喜欢
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2010-12-31
    • 2018-09-16
    相关资源
    最近更新 更多