【发布时间】:2018-09-11 09:06:10
【问题描述】:
我正在尝试用 Java 制作基于文本的游戏。并且我将有很多带有扫描仪的 switch 语句,但我不确定哪种方式最好。
用 Scanner 制作 switch 语句的最佳方法是什么? try+catch 更好吗?还是循环?
如果我有,比如说,10 个 switch 语句。为每个 switch 语句声明 10 个不同的 Scanner 会更好吗?
我喜欢 try+catch 风格的 switch 语句,里面有单独的 Scanner,但是有人说没有必要,这样会浪费太多内存。我更喜欢在输入错误类型时调用该方法,并且我认为 try+catch 以这种方式更好,因为当它被调用时,它还调用了 Scanner 和 Random,让我们有机会重置用户输入的输入还有Random随机生成的数字。
下面的这些代码是示例。 这里的代码不是一个好的代码吗? (只是说到 try+catch,scanner 的用法)
public static void levelUpAsk_111(Character chosenMember) {
try {
Random rand = new Random();
Scanner sc = new Scanner(System.in);
int dicePercent = rand.nextInt(6) + 1;
int num = sc.nextInt();
if (num == dicePercent ) {
System.out.println("** Congratulation!!");
sc.nextLine();
System.out.println("**Which one would you like to increase?");
System.out.println("1. +20 HP");
System.out.println("2. +10 MP");
System.out.println("3. +5 ATT");
levelUpAsk_222(chosenMember); //the second method
} else if (num > 7 || num < 1) {
System.out.println("Please from 1 to 6");
levelUpAsk_111(chosenMember); //recall itself
} else {
System.out.println("** Sorry..");
sc.nextLine();
}
} catch (InputMismatchException e) {
System.out.println("Please integer only");
levelUpAsk_111(chosenMember); //recall itself
}
}
public static void levelUpAsk_222(Character chosenMember) {
try {
Scanner sc = new Scanner(System.in);
int select = sc.nextInt();
switch (select) {
case 1:
System.out.println("** HP has increased by 20.");
break;
case 2:
System.out.println("** MP has increased by 10.");
break;
case 3:
System.out.println("** ATT has incrased by 5.");
break;
default:
System.out.println("From 1 to 3");
levelUpAsk_222(chosenMember); //recall itself
break;
}
} catch (InputMismatchException e) {
System.out.println("Only integer please"); //recall itself
levelUpAsk_222(chosenMember);
}
}
【问题讨论】:
-
您应该总共拥有一台扫描仪。
标签: java switch-statement try-catch java.util.scanner