如何使我的catch块回到方法中的try块?

时间:2018-09-14 02:15:10

标签: java

对于我的java类,我们将要求用户输入,因此我决定创建一个仅返回整数值的方法。当我运行main并输入double时,它将返回0,并且不会返回try块以从用户那里获取另一个值。是不是应该在捕获到异常后返回try块?

import java.util.Scanner;
import java.util.InputMismatchException;


class MyMethods   {


    public static int getInteger()   {

    Scanner keyboard = new Scanner(System.in);
    int  integer = 1;


        try   {

          System.out.println("Please enter integer");
          integer = keyboard.nextInt();

       }   
       catch(InputMismatchException e ) {  //if anything besides an integer is entered we will catch here and go back to try block.

          System.out.println("Please enter integer only!");

      } 


     return integer;

   }


}//end class

下面是测试

class methodTest  {

    public static void main(String[] args)    {


    int integerTest = MyMethods.getInteger();
    System.out.println(integerTest);//prints 0 if double is entered


    }//end main


}//end class

0 个答案:

没有答案