gpt4 book ai didi

java - 扫描仪使 catch 语句崩溃

转载 作者:行者123 更新时间:2023-11-30 06:23:11 25 4
gpt4 key购买 nike

当我尝试在其中使用扫描器时,我遇到了 catch 语句崩溃的问题。我正在为我的计算机科学类(class)制作一个简单的石头剪刀布程序,我的目标是让它几乎不可能崩溃。这是我的代码:

public class RPS {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random gen = new Random();
int rounds = 0, choice, playerchoice = 0, complete, playerwins, compwins;
String cont = "y";

System.out.println("Rock, Paper, Scissors!");

while ("y".equalsIgnoreCase(cont)) {
complete = 0;
playerwins = 0;
compwins = 0;
System.out.println("How many rounds would you like to play?"
+ " (1, best of 3, or best of 5)");

while (true) {

try {
rounds = scan.nextInt();
while (rounds != 1 && rounds != 3 && rounds != 5) {
System.out.println("Invalid number of rounds.");
System.out.println("One game, best of 3, or best of 5?");
rounds = scan.nextInt();
}
break;

} catch (Exception e) {
while (rounds != 1 && rounds != 3 && rounds != 5) {
System.out.println("Invalid number of rounds.");
System.out.println("One game, best of 3, or best of 5?");
rounds = scan.nextInt();
}
}
}

除非 netbeans 在 try block 中抛出 InputMismatchException,否则我的代码将完全正常运行。虽然 catch 语句应该阻止这种事情,但它仍然崩溃,我不知道为什么。

由于我是一名微薄的高中生,对于我可能使用的任何糟糕的编码实践,我深表歉意。我唯一的目标是让它发挥作用。

最佳答案

Try{this}/Catch{that} 就像说“尝试这个,如果那个不起作用,就这样做”。这里的问题是您在 catch block 中放置了与 try block 中相同的代码。想象一下:

  1. 我们进入 Try block
  2. 用户输入的内容无效
  3. 因此,我们进入 catch block
  4. 现在,用户位于 catch block 中,并且输入了无效的内容
  5. 现在我们失败了,但我们无处可去!我们已经进入了 catch block 。
  6. 我们失败了

scan.nextInt();每当它收到无效输入时就会失败,因此每次调用该函数时它都应该在 try block 内。

因此,只需将 catch block 留空(或者只打印“请输入有效的轮数!”而不执行其他操作)即可解决此问题。如果我们在 catch block 中失败,什么也不会发生,我们将进入 while 循环并返回到 try block 进行另一次尝试。

关于java - 扫描仪使 catch 语句崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47717481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com