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

Java如何在多个其他方法中使用某一方法内创建的数组?

问题原因
  • 你代码中定义的myArray、count都是createArray方法的局部变量,局部变量的作用域仅局限在方法内部,方法执行完成后就会被JVM回收,其他方法无权访问,这就是你收到「未解析」报错的核心原因。
  • 除了变量作用域问题,你的代码还有几处逻辑错误:
    • 二维数组遍历逻辑错误:内层循环遍历列时调用了myArray.length(数组行数),行列数不一致时会触发数组越界
    • 下标校验逻辑错误:使用了&&判断,只要行、列其中一个越界就不会被命中;同时未判断等于数组长度的场景(Java数组下标从0开始,最大合法下标为长度-1)
    • 平均值计算为整数除法,会丢失小数精度
    • 元素统计打印位置错误,每打印一行数组就会输出一次总元素数
修复方案(推荐:参数传递)

这种方案没有全局变量污染,符合Java开发规范:

  1. 修改createArray方法返回值为int[][],执行完成后返回创建好的二维数组
  2. 在main方法中接收返回的数组,作为入参传递给calculateVariables和callArray方法
  3. 修正其他逻辑bug

完整修复代码如下:

import java.lang.Math;
import java.util.Scanner;

public class RandomArray {

    public static void main(String[] args) {
        // 接收createArray返回的数组
        int[][] myArray = createArray();
        // 把数组作为参数传递给后续方法
        calculateVariables(myArray);
        callArray(myArray);
    }

    public static int[][] createArray(){
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter number of rows: ");
        int rows = scan.nextInt();
        System.out.print("Enter number of columns: ");
        int columns = scan.nextInt();

        int count = 0;
        int[][] myArray = new int[rows][columns];

        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < columns; col++) {
                myArray[row][col] = (int) (Math.random() * 100);
                System.out.print(myArray[row][col] + "\t");
                count++;
            }
            System.out.println();
        }
        // 总元素数打印移到循环外
        System.out.println("\nThe number of elements in the array: " + count);
        // 返回创建好的数组
        return myArray;
    }
    
    // 方法增加数组入参
    public static void calculateVariables(int[][] myArray){
        int sum = 0;
        int min = myArray[0][0];
        int max = myArray[0][0];
        int below50 = 0;
        // 总元素数可以直接通过数组计算,不用单独传递
        int totalCount = myArray.length * myArray[0].length;

        for (int i = 0; i < myArray.length; i++) {
            // 内层循环取当前行的长度
            for (int j = 0; j < myArray[i].length; j++) {
                if (max < myArray[i][j]) {
                    max = myArray[i][j];
                }
                if (min > myArray[i][j]) {
                    min = myArray[i][j];
                }
                sum = sum + myArray[i][j];
                if (myArray[i][j] < 50) {
                    below50++;
                }
            }
        }
        // 转double避免整数除法丢精度
        System.out.println("The average number is: " + (double)sum / totalCount);
        System.out.println("the min is " + min);
        System.out.println("the max is " + max);
        System.out.println("the number of entries below 50 is: " + below50);
        System.out.println();
    }
    
    // 方法增加数组入参
    public static void callArray(int[][] myArray){
        Scanner scan2 = new Scanner(System.in);
        System.out.print("Enter a row number: ");
        int row1 = scan2.nextInt();
        System.out.print("Enter a column number: ");
        int col1 = scan2.nextInt();

        // 修正下标判断逻辑,只要满足任意一个条件就是非法下标
        if (row1 < 0 || row1 >= myArray.length || col1 <0 || col1 >= myArray[row1].length) {
            System.out.println("Sorry, I cant retrieve that value! You entered a bad index.");
        } else {
            System.out.println("The entry at that row and column is: " + myArray[row1][col1]);
        }
    }
}
可选方案:静态成员变量

如果不想频繁传递参数,也可以把数组定义为类的静态成员变量,所有静态方法都可以直接访问,不过这种方式会延长变量生命周期,多场景修改容易出现变量污染,仅适合小型测试项目使用:

public class RandomArray {
    // 定义静态成员变量
    static int[][] myArray;
    static int count;

    public static void main(String[] args) {
        createArray();
        calculateVariables();
        callArray();
    }

    public static void createArray(){
        // 其他逻辑不变,创建数组时直接给静态变量赋值
        // ...原有逻辑
        myArray = new int[rows][columns];
        // ...原有逻辑
        count = rows * columns;
    }
    // 后续方法不需要加参数,直接使用myArray和count即可
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:09:03