【问题标题】:Catch repeats String twice捕获重复字符串两次
【发布时间】: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


【解决方案1】:

Catch 块不会重复两次。方法setGameRounds() 在某些条件下递归调用自身,只要满足这些条件,它就会一次又一次地执行该方法的第一行。如果您想避免这些,请在调用方法setGameRounds()之前将行放在原始调用者方法中@

【讨论】:

    猜你喜欢
    • 2018-03-22
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    相关资源
    最近更新 更多