如何修复Java中的InputMismatchException异常?
Hey there! Let's break down why you're hitting that InputMismatchException only when entering 10+ digit numbers made of 3s and 7s, and how to fix it.
The Root Cause
Here's the core issue: Java's int type has a strict range—it can only hold values from -2147483648 to 2147483647. A 10-digit number made of 3s and 7s (like 3333333333) is already 3.3 billion, which is way larger than the maximum int value (2.1 billion). When you call input.nextInt(), the Scanner can't fit that huge number into an int variable, so it throws the InputMismatchException. Shorter numbers work because they fall within the int range.
Solution 1: Switch to long for Larger Numeric Range
If you want to keep working with numeric types, swap int for long—it can hold values up to 9 quadrillion, which covers way more digits than you're likely to input. Here's how to adjust your code:
Scanner input = new Scanner(System.in); System.out.print("Enter a positive integer..."); // Use nextLong() instead of nextInt() long num = input.nextLong(); // Update your helper methods (numberDigits, firstNum, lastNum) to accept long parameters 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));
Solution 2: Use String for Maximum Flexibility
Since you only need to check the number of digits, first digit, and last digit, working directly with a String is even simpler. It avoids any numeric range limits entirely, and you can replace your helper methods with straightforward string operations:
Scanner input = new Scanner(System.in); System.out.print("Enter a positive integer..."); String numStr = input.next(); // Optional: Validate input is a valid positive integer if (!numStr.matches("\\d+")) { System.out.println("Whoops, please enter a valid positive integer with no non-digit characters!"); return; } // Get digit count, first, and last digits directly from the string int digitCount = numStr.length(); char firstDigit = numStr.charAt(0); char lastDigit = numStr.charAt(numStr.length() - 1); System.out.println("Number of digits in number is " + digitCount); System.out.println("Number begins with " + firstDigit); System.out.println("Number ends with " + lastDigit);
This approach is perfect if you might ever need to handle numbers longer than 19 digits (the limit for long).
内容的提问来源于stack exchange,提问作者Jolly_Jimmy

