此程序采用整数并返回该整数内的位数。我注意到我无法获取非常大的数字,因此我决定使用BigInteger类。一切都很好,直到我意识到我需要用户输入有效的整数,如果他们使用不兼容的输入(如字符串)。如何在catch语句之后重复使用main方法,因此无论您使用错误输入多少次,它都会请求另一个输入?我知道我不应退出该计划。
//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);}}
答案 0 :(得分:0)
你可以循环:
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.");
}
}
}
答案 1 :(得分:0)
有点像伪代码会这样做:
main(args) {
input = null;
do {
input = getInput();
} while(!valid(input);
solveAlgorithm(input);
}