Java初学者:使用Scanner创建一维数组的方法编译报错如何解决?
Fixing Your Scanner-Based Array Creation Code
Hey there! Let's walk through fixing your code—you've got a good start, but there are a few small issues tripping up the compiler and functionality. Let's break down what's wrong first, then fix it step by step.
What's Causing the Compilation & Functionality Issues?
- Undefined variable
sclavier: In yourmainmethod, you're trying to passsclaviertosaisir(), but you never declared or initialized this array. That's a straight-up compile error. - Uninitialized array parameter: Even if you declared
sclavierinmain, passing an uninitialized array (likeString[] sclavier;withoutnew String[5]) would cause aNullPointerExceptionbecause the array has no memory allocated for its elements. - Redundant Scanner creation: You're creating a new
Scannerinstance every time the loop runs—this is inefficient and unnecessary. - Method design mismatch: Your goal is to create an array, but your current
saisirmethod expects an array to be passed in. We can adjust this to make the method handle array creation itself, which aligns better with your goal.
Fixed Code: Let the Method Create & Return the Array
This version makes the saisir method responsible for creating the array, filling it with user input, and returning it to the main method—clean and straightforward.
package my_train_1; import java.util.Scanner; public class Use_methods { public static void main(String[] args) { // Call our method to get the filled array String[] userInputs = saisir(); System.out.println("voila les nouvelles chaines de caractéres que vous vennez de saisir"); // Loop through and print each input for (String input : userInputs) { System.out.println(input); } } // Modified method: returns a fully created and filled String array public static String[] saisir() { // Create an array of length 5 (allocate memory for 5 elements) String[] inputArray = new String[5]; // Create Scanner ONCE outside the loop (more efficient) Scanner reader = new Scanner(System.in); int p = 0; while (p < inputArray.length) { // Use array length instead of hardcoding 5 System.out.print("saisir une chaine de caracter: "); inputArray[p] = reader.nextLine(); p++; } // Close the Scanner to free up resources reader.close(); // Return the filled array to the caller return inputArray; } }
Key Changes Explained
- Method return type updated: Changed
saisirfromvoidtoString[]so it can return the created array. - Array creation inside the method: We initialize the array with
new String[5]directly insaisir, so we don't have to pass an uninitialized array frommain. - Scanner optimization: Only create one
Scannerinstance and close it after the loop—no more redundant object creation. - Flexible loop condition: Use
inputArray.lengthinstead of hardcoding5, so if you change the array length later, you don't have to update the loop too.
Alternative: Pass an Initialized Array (If You Prefer)
If you want the main method to handle array creation (e.g., to set a custom length), here's another working version:
package my_train_1; import java.util.Scanner; public class Use_methods { public static void main(String[] args) { // Initialize the array first (allocate memory for 5 elements) String[] sclavier = new String[5]; // Pass the initialized array to be filled saisir(sclavier); System.out.println("voila les nouvelles chaines de caractéres que vous vennez de saisir"); for (String input : sclavier) { System.out.println(input); } } // Method takes an already initialized array and fills it public static void saisir(String[] sclavier) { Scanner reader = new Scanner(System.in); int p = 0; while (p < sclavier.length) { System.out.print("saisir une chaine de caracter: "); sclavier[p] = reader.nextLine(); p++; } reader.close(); } }
Quick Java Array Basics to Remember
- Arrays in Java need to be initialized with
new Type[length]before you can store elements in them—otherwise, they're just null references. - If a method's job is to create an object (like an array), having it return that object is usually the cleanest approach.
- Always close IO resources like
Scannerwhen you're done with them to avoid resource leaks.
内容的提问来源于stack exchange,提问作者moradov
相关产品推荐
相关产品推荐

