【问题标题】:Why isn't my method populating my array with null?为什么我的方法不使用 null 填充我的数组?
【发布时间】:2023-02-19 23:45:55
【问题描述】:

我需要创建一个程序来显示表格数组的内容,每个表格都有宽度和高度。

public class Table {
    private static int width;
    private static int height=20;
    private static final Table[] tables = new Table[10];

    public Table(int width, int height) {
        this.width=width;
        this.height=height;
    }
    public int getWidth() {
        return width;
    }
    public int getHeight() {
        return height;
    }

    public static Table[] getTables() {
        return tables;
    }

    public static int tableWidth(){
        int widthMin=50;
        int widthMax=200;
        width= widthMin+ (int) (Math.random()*(widthMax-widthMin));
        return width;
    }
    public static Table fillArray(){
        int i;
        for (i=0; i<tables.length-1;i++){
            tables[i]=new Table(tableWidth(),height);
        }
      return tables[i];
    }

    @Override
    public String toString() {
        return tables + "";
    }
}

public class Main {
    public static void main(String[] args) {

        for (int i=0;i<Table.getTables().length;i++){
            System.out.println(Table.fillArray());
        }
    }
}

为什么填充数组的方法不是在所有位置都呈现空值?

【问题讨论】:

  • 是什么目的public static Table fillArray(){ .. } 方法?你是什​​么认为/假设它应该做什么?
  • 当您开始将所有内容设为静态时发出红旗。

标签: java arrays for-loop


【解决方案1】:

我猜问题出在填充数组()方法。尝试将每个表添加到 for 循环内的表数组中,然后返回整个数组?

我不确定当前是否所有表都被您的 for 循环实现所填充。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多