[英]Java Switch Case with multiple inputs
I'm trying to do a tamagotchi , and I would like it to be possible for the object to recieve more than one command from the same scanner.我正在尝试执行tamagotchi ,并且我希望对象能够从同一扫描仪接收多个命令。 So when I type "sleep", that afterwards I can write in the console the next thing that it should do like "eat".
所以当我输入“sleep”时,之后我可以在控制台中写下它应该做的下一件事,比如“吃”。
Here's the code:这是代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Tamagotchi blue = new Tamagotchi("Lenns", 8, 4, 6, 7);
Scanner scanner = new Scanner(System.in);
String Input = scanner.nextLine();
switch (Input) {
case "Eat":
blue.eat();
break;
case "Sleep":
blue.sleep();
break;
case "Sport":
blue.sport();
break;
case "Condition":
blue.output();
break;
default: System.out.println("no valid option");
break;
}
I hope you understand my question and can help me.我希望你能理解我的问题并能帮助我。
Thank you very much for your precious time.非常感谢您的宝贵时间。
For repeating a segment of code you need a loop, in your case, wrap the reading of the user input and the switch-case so the actions can be repeated为了重复一段代码,您需要一个循环,在您的情况下,包装用户输入和开关案例的读取,以便可以重复操作
String Input = null;
while(true){
Input = scanner.nextLine();
switch (Input) {
case "Eat":
blue.eat();
break;
case "Sleep":
blue.sleep();
break;
case "Sport":
blue.sport();
break;
case "Condition":
blue.output();
break;
default: System.out.println("no valid option");
break;
}
Some small tweak to the answer above对上述答案的一些小调整
String Input = null;
while(true){
try{
Input = scanner.nextLine();
switch (Input) {
case "Eat":
blue.eat();
break;
case "Sleep":
blue.sleep();
break;
case "Sport":
blue.sport();
break;
case "Condition":
blue.output();
break;
default:
throw new IllegalArgumentException("Invalid operation");
}
}catch(IllegalArgumentException e){
System.out.println(e.getMessage());
}
}
If u use this variation, u need to add a "quit" case or similar to be able to break the loop.如果你使用这个变体,你需要添加一个“退出”案例或类似的东西才能打破循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.