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. 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? 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.