【发布时间】:2020-10-04 18:38:04
【问题描述】:
我是初学者,我需要一些帮助。 我必须在我的大学里做一个项目。这是一个简单的游戏。
在这种方法中,我可以选择要玩多少轮。
If number is less than 5 and more than 30 program will say - "You need to choose between 5 and 30!"
If I type letters or words, program will say - "You cannot type letters/words here!" + "Please, try again. Choose between 5 - 30"
我有while和try catch,所以如果我输入错误,程序仍然会运行。
所以我的问题是:为什么 catch 在我的代码中重复两次?
控制台:
How many rounds do you want to play? (5-30)
You cannot type letters/words here!Please, try again. Choose between 5 - 30
How many rounds do you want to play? (5-30)
代码
private void setGameRounds() {
System.out.println("How many rounds do you want to play? (5-30)");
while (true) {
try {
gameRounds = scan.nextLine();
int gameRoundsInt = Integer.parseInt(gameRounds);
if (gameRoundsInt >= 5 && gameRoundsInt <= 30) {
System.out.println("You will play " + gameRoundsInt + " rounds.");
break;
} else {
System.out.println("You need to choose between 5 and 30!");
setGameRounds();
break;
}
} catch (Exception e) {
System.out.println("You cannot type letters/words here!" +
"Please, try again. Choose between 5 - 30");
setGameRounds();
}
}
}
【问题讨论】:
-
while(true)的目的是再次自动执行代码,所以不要在其内部调用setGameRounds()那样无用且无法执行您想要的操作 -
为了帮助您,请粘贴minimal reproducible example,而不是我们无法编译的部分代码。
标签: java recursion while-loop try-catch