如何使用try catch java?

时间:2017-09-30 02:27:20

标签: java loops try-catch do-while

对于我的一个赋值,我们应该尝试捕获一个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}

有关如何使这项工作的任何想法?

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:0)

  

“输入两次输入”

因为您有两行要求输入数字:

menuOptions.nextInt();