我是Java的新手。
我目前正在做一个附带项目;制作基于文字的游戏。我意识到使用Switch语句对于这种类型的游戏非常有用。
基本上就是它的工作原理。
我问用户,您想做什么?
那么,构建switch
语句和Scanner
以及“再次询问用户的默认语句”的最佳方法是什么?
我一直在这样做(我的代码在这里),但是似乎有很多潜在的问题。
你们能给我一些如何用switch
做出最佳Scanner
陈述的提示吗?
非常感谢您。
public static void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("What do you want to do?");
while (!sc.hasNextInt()) {
sc.next();
}
select = sc.nextInt();
switch (select) {
case 1:
eat();
break;
case 2:
walk();
break;
case 3:
sleep();
break;
default:
System.out.println("choose from 1 to 3");
ask(); //would you re call itself again here? or is there any otherway to do without recalling itself?
}
答案 0 :(得分:1)
您的代码似乎还可以,但我会对其进行重构。还添加while循环以再次询问:
public static void ask() {
Scanner sc = new Scanner(System.in);
boolean isWrongAnswer;
do {
isWrongAnswer = false;
System.out.println("What do you want to do?");
switch (sc.nextInt()) {
case 1:
eat();
break;
case 2:
walk();
break;
case 3:
sleep();
break;
default:
System.out.println("choose from 1 to 3");
isWrongAnswer = true;
}
} while (isWrongAnswer);
}
答案 1 :(得分:0)
最好先检查扫描仪是否有东西,然后再检查它是否为int值。为此,可以使用如下所示的sc.hasNext()和sc.hasNextInt(),
public static void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("What do you want to do?");
while (sc.hasNext()) {
int select = 0;
if (sc.hasNextInt()) {
select = sc.nextInt();
}
switch (select) {
case 1:
System.out.println("call eat()");
break;
case 2:
System.out.println("call walk()");
break;
case 3:
System.out.println("call sleep()");
break;
default:
System.out.println("choose from 1 to 3");
ask();
}
}
答案 2 :(得分:0)
我建议您在这种情况下使用String。提高代码的可读性并避免错误。(http://www.oracle.com/technetwork/java/codeconventions-150003.pdf)
private static final String EAT = "1";
private static final String WALK = "2";
private static final String SLEEP = "3";
public void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("What do you want to do?");
switch (sc.next()) {
case EAT:
eat();
break;
case WALK:
walk();
break;
case SLEEP:
sleep();
break;
default:
System.out.println("choose from 1 to 3");
ask(); // as described above via "do while", but there is nothing wrong with recursion. The garbage collector works.
}
}