【问题标题】:Ackermans' Function Try Catch issueAckermans 的函数 Try Catch 问题
【发布时间】:2017-07-21 18:25:03
【问题描述】:

我目前正在处理 Ackerman 函数问题,我们必须为用户输入编写故障安全代码。因此,如果通常会使程序崩溃的用户输入,它只会发送一条消息。我能够找出整数值是否太大的异常,但我不知道如何检查用户输入是否为整数。我尝试使用“InputMismatchException”捕获块,但代码开始混乱和出错,或者根本不起作用。

public static void main(String[] args) {

//creates a scanner variable to hold the users answer
Scanner answer = new Scanner(System.in);


//asks the user for m value and assigns it to variable m
System.out.println("What number is m?");
int m = answer.nextInt();




//asks the user for n value and assigns it to variable n
System.out.println("What number is n?");
int n = answer.nextInt();


try{
//creates an object of the acker method
AckerFunction ackerObject = new AckerFunction();
//calls the method
System.out.println(ackerObject.acker(m, n));
}catch(StackOverflowError e){
    System.out.println("An error occured, try again!");
}



}

}

【问题讨论】:

    标签: java try-catch ackermann


    【解决方案1】:

    你必须放

    int n = answer.nextInt();
    

    在 try 块中。 然后你可能会捕获 java.util.InputMismatchException

    这对我有用:

    public static void main(String[] args) {
    
        //creates a scanner variable to hold the users answer
        Scanner answer = new Scanner(System.in);
    
        int m;
        int n;
        try{
            //asks the user for m value and assigns it to variable m
            System.out.println("What number is m?");
            m = answer.nextInt();
            //asks the user for n value and assigns it to variable n
            System.out.println("What number is n?");
            n = answer.nextInt();
        }catch(InputMismatchException e){
            System.out.println("An error occured, try again!");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-23
      • 1970-01-01
      • 2011-11-28
      • 2011-08-26
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多