[英]Java InputMismatchException error. How would I go about fixing this?
It only appears when I enter 10 or more numbers that are 3's and 7's. 仅当我输入10个或更多3和7的数字时才会显示。 It is coming from this method below, I tested it without this method. 它来自下面的此方法,我没有使用此方法对其进行了测试。 Here is the code 这是代码
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);
}
}
The Scanner
is attempting to read an int
with the nextInt
method . Scanner
正在尝试使用nextInt
方法读取一个int
。
An invocation of this method of the form
nextInt()
behaves in exactly the same way as the invocationnextInt(radix)
, whereradix
is the default radix of this scanner. 调用nextInt()
形式的此方法的行为与调用nextInt(radix)
行为完全相同,其中radix
是此扫描器的默认基数。
Throws: 抛出:
InputMismatchException
- if the next token does not match the Integer regular expression, or is out of rangeInputMismatchException
如果下一个标记与Integer正则表达式不匹配或超出范围
If you enter a value larger than Integer.MAX_VALUE
(about 2.1 billion, 10 digits), then you will get an InputMismatchException
. 如果输入的值大于Integer.MAX_VALUE
(约21亿,10位数字),则将收到InputMismatchException
。
If you want to enter up to 19 digits, use nextLong
. 如果要输入最多19位数字,请使用nextLong
。
If you want to enter an arbitrary number of digits, just call next
, get the string, and validate that it only contains digits. 如果要输入任意位数,只需调用next
,获取字符串,并验证它仅包含数字即可。 You'll need to convert the character digits to a numeric type before further processing. 您需要先将字符数字转换为数字类型,然后再进行进一步处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.