gpt4 book ai didi

java - 如何退出 switch 语句并返回到 While 循环?

转载 作者:太空宇宙 更新时间:2023-11-04 09:13:09 26 4
gpt4 key购买 nike

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

}

}
}

最佳答案

一旦进入循环,您就永远不会更新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 .

关于java - 如何退出 switch 语句并返回到 While 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59440420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com