简体   繁体   English

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

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

This program takes in an integer and returns the number of digits within that integer. 该程序采用一个整数,并返回该整数内的位数。 I noticed that I was unable to take very big numbers, so I decided to use the BigInteger class. 我注意到我无法接受很大的数字,所以我决定使用BigInteger类。 All was good until I realized I needed the user to input a valid integer if they use incompatible input (like a string). 一切都很好,直到我意识到如果他们使用不兼容的输入(例如字符串),我需要用户输入一个有效的整数。 How do I make the main method repeat after the catch statement, so no matter how many times you use bad input it request another input? 如何使catch方法在catch语句之后重复,所以无论您使用错误的输入多少次,它都会请求另一个输入? I know that I shouldn't exit the program. 我知道我不应该退出程序。

//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);}}    

You can loop : 您可以循环:

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.");
      }
    }
}

Somewhat like this pseudocode would do: 类似于此伪代码的代码可以做到:

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