仅当我输入10个或更多的3和7的数字时才会出现。它来自下面的这个方法,我没有这种方法测试它。这是代码
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive integer...");
int num = input.nextInt();
// Outputs
System.out.println("Number of digits in number is " + numberDigits(num));
System.out.println("Number begins with " + firstNum(num));
System.out.println("Number ends with " + lastNum(num));
System.out.println("Does number begin with 7? " + beginWith(num, 7));
System.out.println("Does number begin with 3? " + beginWith(num, 3));
System.out.println("Does number contain a 7? " + contains(num, 7));
System.out.println("Does number contain a 3? " + contains(num, 3));
System.out.println("Is the number divisible by 13? " + divTest(num, 13));
System.out.println("Is the number divisible by 77? " + divTest(num, 77));
System.out.println("How many times does 7 appear in the number? " + digitAppearances(num, 7));
System.out.println("How many times does 3 appear in the number? " + digitAppearances(num, 3));
public static int digitAppearances(int num, int x) {
// Check if num is 0
if (num <= 0 ) {
return 0;
}
// Count number of times x appears
else if (num % 10 == x) {
return 1 + digitAppearances(num / 10, x);
}
else {
return digitAppearances(num / 10, x);
}
}
答案 0 :(得分:1)
Scanner
正在尝试使用the nextInt
method阅读int
。
调用
nextInt()
形式的此方法的行为与调用nextInt(radix)
完全相同,其中radix
是此扫描程序的默认基数。
<强>抛出:强>
InputMismatchException
- 如果下一个标记与整数正则表达式不匹配,或者超出范围
如果您输入的值大于Integer.MAX_VALUE
(约21亿,10位数),那么您将获得InputMismatchException
。
如果您想输入最多19位数字,请使用nextLong
。
如果要输入任意数量的数字,只需调用next
,获取字符串,并验证它只包含数字。在进一步处理之前,您需要将字符数字转换为数字类型。