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