【问题标题】:How do I insert my data into a 2D multidimensional array?如何将我的数据插入二维多维数组?
【发布时间】:2025-12-19 03:35:11
【问题描述】:

我有一个衣服对象的变量(销售额、成本、价格和收益),我想插入到二维数组中。我可以毫无问题地使用 for 循环创建我需要的 4x4 2D 数组。我的问题是将数据插入到数组中。

例如,如果我创建一个对象dress(3000, 50, 10, 36000),有没有办法让我将 3000、50、10 和 36000 插入第一行,然后继续使用第二行排是裤子,第三排裙子等等?我发现很难将数据放入数组中,而不是简单地逐行逐行并将它们一个接一个地写在括号中。有没有更高效、更简洁的方式来编写代码并将数据插入到数组中?

谢谢

【问题讨论】:

  • Initialize 2D array的可能重复
  • @PHILLAM 为什么不使用List 并创建类,例如Cloth?
  • 任务是创建一个表格,其中包含将在控制台上打印的每件衣服的销售、成本、价格和收益。我使用这 4 个参数从一个类中创建了对象。除了像这样{{3000,6,90,88},{4700,88,77,63} ....跨度>

标签: java multidimensional-array


【解决方案1】:

我将从创建一个服装类开始:

public class Clothing {

    private int sales, cost, price, benefits;

    public Clothing(int sales, int cost, int price, int benefits) {
        this.sales = sales;
        this.cost = cost;
        this.price = price;
        this.benefits = benefits;
    }

    public int getSales() {
        return sales;
    }

    public int getCost() {
        return cost;
    }

    public int getPrice() {
        return price;
    }

    public int getBenefits() {
        return benefits;
    }

}

然后您可以将所有服装对象放入一个数组(一维)中,并遍历它以填充二维数组(使用 Clothing 类中的 getter 方法):

//Make a clothes array
Clothing[] clothes = new Clothing[4];
//Fill it
clothes[0] = new Clothing(3000, 50, 10, 36000); //Dress
clothes[1] = new Clothing(4500, 40, 13, 35600); //Pants
//etc...

//Make your 2D array
int[][] array = new int[clothes.length][4];

//Fill it
for(int i = 0; i < clothes.length; i++) {
    array[i][0] = clothes[i].getSales();
    array[i][1] = clothes[i].getCost();
    array[i][2] = clothes[i].getPrice();
    array[i][3] = clothes[i].getBenefits();
}

【讨论】: