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

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 your main method, you're trying to pass sclavier to saisir(), but you never declared or initialized this array. That's a straight-up compile error.
  • Uninitialized array parameter: Even if you declared sclavier in main, passing an uninitialized array (like String[] sclavier; without new String[5]) would cause a NullPointerException because the array has no memory allocated for its elements.
  • Redundant Scanner creation: You're creating a new Scanner instance every time the loop runs—this is inefficient and unnecessary.
  • Method design mismatch: Your goal is to create an array, but your current saisir method 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

  1. Method return type updated: Changed saisir from void to String[] so it can return the created array.
  2. Array creation inside the method: We initialize the array with new String[5] directly in saisir, so we don't have to pass an uninitialized array from main.
  3. Scanner optimization: Only create one Scanner instance and close it after the loop—no more redundant object creation.
  4. Flexible loop condition: Use inputArray.length instead of hardcoding 5, 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 Scanner when you're done with them to avoid resource leaks.

内容的提问来源于stack exchange,提问作者moradov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:34:21