[英]How can i exit switch statement and get back to While loop?
所以我正在尝试的是,在我通过其中一个搜索获得足够的结果后,转到另一个搜索。 换句话说,我想退出 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!");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.