我正在尝试用Java制作基于文本的游戏。而且我将使用扫描仪进行很多切换,但是我不确定哪种方法是最好的。
使用Scanner进行开关声明的最佳方法是什么? try + catch更好吗?还是循环?
,如果我有10个切换语句。为每个开关语句声明10个不同的Scanner更好吗?
我喜欢使用try + catch样式的开关语句,其中包含单个Scanner,但是有人说这是没有必要的,这样会浪费太多内存。我更喜欢在输入错误的类型输入时调用该方法,并且我认为try + catch会更好,因为调用该方法时,它还会调用Scanner和Random,从而使我们有机会重置用户输入的输入以及随机产生的随机数。
下面的这些代码是示例。 这里的代码不是很好的代码吗? (仅在try + catch和扫描仪用法方面)
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);
}
}
答案 0 :(得分:0)
对于switch语句,不需要每次都要使用新的Scanner
对象。您可以在每个方法的开头声明一次。如果您必须在代码中处理多个Scanner
对象,则比只有一个对象更令人困惑。
您可以使用带有default:
的开关循环菜单来捕获未列出的输入。例如
switch (option){ //assuming you declared option to an int and user has inputted a value for it
case 1:
{
//put some code here
break;
}
case 2:
{
//put more code here
break;
}
case 0:
{
//used to exit the loop
break;
}
default:
{
System.out.println("Please enter a integer only");
levelUpAsk_111(chosenMember); //you can do it this way, or use a do-while looped switch menu that keeps asking until a valid int is input
}
}