首页 > 解决方案 > 使用默认构造函数初始化声明的数组

问题描述

现在我正在为我的学校做一个练习。练习要求我将数组声明为私有,然后仅通过构造函数对其进行实例化。代码看起来像这样。问题是 sepulcher 就像一个局部变量一样工作,我想稍后使用它。添加“这个”。在它面前不起作用。我能做些什么?

public class Mapland extends Thread {
private int groining;
private int[] sepulcher;

public Mapland(int[] b) {
    int[] sepulcher = new int[b.length];

}

public int getGroining() {
    return this.groining;
}

public void run() {
    groining = Integer.MIN_VALUE;
    for (int i = 0; i < sepulcher.length; i++) {
        if (getGroining() < this.sepulcher[i]) {
            this.groining = this.sepulcher[i];
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

标签: arrayslocalprivateinstantiationdeclare

解决方案


在构造函数中,您不初始化全局私有数组,而是创建一个新数组。要初始化它,您只需要在没有前一个 (int[]) 的情况下调用它,因为您之前已经声明了它。您在构造函数中的代码应该是:

sepulcher = new int[b.length];

推荐阅读