【问题标题】:How to use try catch java?如何使用try catch java?
【发布时间】:2017-09-30 02:27:19
【问题描述】:

对于我的一项任务,我们应该尝试捕获 InputMismatchException 并告诉用户输入给定的选项(在这种情况下,它可以是 1、2、3、4,没有别的)。出于某种原因,每当我尝试创建 try catch 块时,它都会让用户输入两次,但它仍然会使程序崩溃。这是我所拥有的:

do {
      Scanner menuOptions = new Scanner(System.in);
      System.out.println("1. Get another card");
      System.out.println("2. Hold hand");
      System.out.println("3. Print statistics");
      System.out.println("4. Exit"+ "\n");
      System.out.println("Choose an Option: ");
      int selectedOption = menuOptions.nextInt();

      try{
      selectedOption = menuOptions.nextInt();
      }

      catch(InputMismatchException e){
      System.out.println("Invalid input! Please select between options 1,2,3,4")
      }


      if (selectedOption == 1) {
      //proceeds to do what is instructed if user input is 1}
      else if (selectedOption ==2{
      //proceeds to do what is instructed if user input is 2}
     else if (selectedOption == 3) {
      //proceeds to do what is instructed if user input is 3}
     else if (selectedOption ==4{
      //proceeds to do what is instructed if user input is 4}

知道如何使这项工作发挥作用吗?

【问题讨论】:

标签: java loops try-catch do-while


【解决方案1】:

这是因为您拨打了两次menuOptions.nextInt()。一次初始化,第二次在try catch 块中。我假设您有要运行的代码,直到用户输入有效的输入,即 1、2、3 或 4。

试试这个:

int selectedOption;
while(true) {
    try {
        selectedOption = menuOptions.nextInt();
        break;
    } catch(InputMismatchException ime) {
        System.out.println("Invalid input! Please select between options 1,2,3,4");
        menuOptions = new Scanner(System.in);
    }
}

【讨论】:

  • 很抱歉,您能否再向我解释一下,我有点迷路了。我试过你说的,但程序还是崩溃了。
【解决方案2】:

"输入两次"

因为你有两行要求一个数字:

menuOptions.nextInt();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    相关资源
    最近更新 更多