You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Java中的InputMismatchException异常?

Fixing InputMismatchException for Large 3/7 Digit Numbers in Java

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:23:08