繁体   English   中英

捕获异常后重复执行main方法

[英]Making a main method repeat after catching an exception

该程序采用一个整数,并返回该整数内的位数。 我注意到我无法接受很大的数字,所以我决定使用BigInteger类。 一切都很好,直到我意识到如果他们使用不兼容的输入(例如字符串),我需要用户输入一个有效的整数。 如何使catch方法在catch语句之后重复,所以无论您使用错误的输入多少次,它都会请求另一个输入? 我知道我不应该退出程序。

//This class test the recursive method to see how many digits are in a number
public class TestDigits {

    public static void main(String[] args) {// main method to test the nmbDigits method
        Scanner intInput = new Scanner(System.in);
        try{
        System.out.println("Input an integer number:");
        BigInteger number = intInput.nextBigInteger() ;
        System.out.println(nmbDigits(number));}

        catch (InputMismatchException ex){
        System.out.println("incorrect input, integer values only.");
        System.exit(1);}}



static BigInteger nmbDigits(BigInteger c) {//nmbDigits method takes input from user and returns the number of digits
    long digits = 0;

    if (c.divide(BigInteger.valueOf(10l)) == BigInteger.valueOf(0l)){
        digits++;
    }
    else if (c.divide(BigInteger.valueOf(10l)) != BigInteger.valueOf(0l)){
        digits++;
          BigInteger remainingValue = c.divide(BigInteger.valueOf(10l));
          BigInteger g =   nmbDigits(remainingValue);
          digits += g.longValue();}
    return BigInteger.valueOf(digits);}}    

您可以循环:

public static void main(String[] args) {// main method to test the nmbDigits method
    boolean exit=false;
    Scanner intInput = new Scanner(System.in);
    while (!exit) {
      try{
        System.out.println("Input an integer number:");
        BigInteger number = intInput.nextBigInteger() ;
        System.out.println(nmbDigits(number));
        exit=true;
      }
      catch (InputMismatchException ex){
        System.out.println("incorrect input, integer values only.");
      }
    }
}

类似于此伪代码的代码可以做到:

main(args) {
   input = null;
   do {
      input = getInput(); 
   } while(!valid(input);
   solveAlgorithm(input);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM