所以我要尝试的是,在我通过一项搜索获得足够的结果而转到另一项搜索之后。换句话说,我想退出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!");
}
}
}
答案 0 :(得分: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!");
}
}