Java存储整数输入为数组时遭遇NumberFormatException问题求助
Hey there, let's break down why you're running into that NumberFormatException when using parseInt() for your array input program—this is a super common issue, and we can fix it easily!
Common Causes & Solutions
1. Leftover Newline Character After Reading Array Size
This is the most frequent culprit. When you use nextInt() to read the array size, it only grabs the numeric value and leaves the newline character (\n) in the input stream. Then when you call nextLine() to read the array elements, it picks up that empty newline instead of the actual input line. Parsing an empty string with parseInt() will immediately throw the exception.
Fix: Add an extra scanner.nextLine() right after nextInt() to "consume" the leftover newline:
int size = scanner.nextInt(); scanner.nextLine(); // Critical: clears the remaining newline String elementsInput = scanner.nextLine();
2. Non-Numeric Characters or Extra Spaces in Input Elements
If your input line has anything other than digits (like letters, commas, or special characters), or even if elements have unexpected leading/trailing spaces (though parseInt handles leading/trailing spaces, cleaning them up avoids edge cases), you'll get the exception.
Fix: Trim each element string before parsing, and split the input line using a regex that handles multiple spaces:
String[] elementStrings = elementsInput.split("\\s+"); // Splits on 1+ spaces for (int i = 0; i < size; i++) { // Trim to remove any accidental leading/trailing spaces array[i] = Integer.parseInt(elementStrings[i].trim()); }
3. Mismatch Between Declared Array Size and Actual Input Elements
If you say the array size is 5 but only enter 4 elements (or 6), you'll either try to parse an empty string (if short) or go out of bounds (if long)—both scenarios can trigger exceptions.
Fix: Add a check to verify the number of elements matches the declared size before parsing:
if (elementStrings.length != size) { System.out.println("Oops! You entered " + elementStrings.length + " elements, but we expected " + size); return; // Exit early to avoid errors }
Full Working Example
Here's a complete code snippet that addresses all these issues:
import java.util.Scanner; public class ArrayInputHandler { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Read array size System.out.print("Enter array size: "); int size = scanner.nextInt(); scanner.nextLine(); // Clear the newline after nextInt() // Read element line System.out.print("Enter " + size + " space-separated elements: "); String inputLine = scanner.nextLine(); String[] elementStrings = inputLine.split("\\s+"); // Validate element count if (elementStrings.length != size) { System.err.println("Error: Element count mismatch! Expected " + size + ", got " + elementStrings.length); scanner.close(); return; } // Parse elements into array int[] array = new int[size]; try { for (int i = 0; i < size; i++) { array[i] = Integer.parseInt(elementStrings[i].trim()); } } catch (NumberFormatException e) { System.err.println("Error: Invalid number found - '" + e.getMessage().split(": ")[1] + "' is not a valid integer."); scanner.close(); return; } // Verify the result System.out.println("Success! Your array:"); for (int num : array) { System.out.print(num + " "); } scanner.close(); } }
Test It With Your Sample Case
Input:
5 1 2 3 4 5
This should run without any exceptions and output your array correctly.
内容的提问来源于stack exchange,提问作者Inherited Geek

