我正在尝试用Java做一个基于文本的游戏。我会有很多关于scanner的切换语句,但是我不确定哪种方式是最好的。
用Scanner制作switch-statement的最好方法是什么?try+catch更好吗?或者做循环?
如果我有,假设有10个switch-statement。为每个switch语句声明10个不同的Scanner是不是更好?
我喜欢有try+catch风格的开关声明与个人扫描器在它,但有人说这是没有必要的,并采取太多的浪费内存的方式。
下面的代码是示例。这里的代码不是一个好的代码吗?(当涉及到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);
}
}发布于 2018-09-11 22:13:27
对于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
}
}https://stackoverflow.com/questions/52272423
复制相似问题