【问题标题】:How do I make my catch block go back to the try block in my method?如何让我的 catch 块回到我的方法中的 try 块?
【发布时间】:2018-09-14 02:15:10
【问题描述】:

对于我的 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

【问题讨论】:

    标签: java


    【解决方案1】:

    这里的一个选择是使用循环来不断提示用户输入,直到收到有效值:

    public int getInteger() {
        Scanner keyboard = new Scanner(System.in);
        Integer value = null;
    
        while (value == null) {
            try {
                System.out.println("Please enter integer");
                value = keyboard.nextInt();
            }
            catch (InputMismatchException e) {
                System.out.println("Please enter integer only!");
            }
        }
    
        return value;
    }
    

    【讨论】:

    • 感谢您的帮助。当我出于某种原因尝试循环时,jGrasp 没有保存。
    【解决方案2】:

    这可能会有所帮助!!!

    public int getInteger() {
        Scanner keyboard = new Scanner(System.in);
        int iValue = 0;
        boolean bCorrect = false;
        while (!bCorrect) {
            try {
                System.out.println("Please enter integer");
                iValue = keyboard.nextInt();
                bCorrect = true; // you can also use break; to move out of the loop.
            }
            catch (InputMismatchException e) {
                System.out.println("Please enter integer only!");
                continue;
            }
        }
        return iValue ;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-24
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      相关资源
      最近更新 更多