java - 如何将数据插入二维多维数组?

标签 java multidimensional-array

我有来自衣服对象的变量(销售、成本、价格和 yield ),我想将它们插入到二维数组中。我可以使用 for 循环创建我需要的 4x4 2D 数组,没有任何问题。我的问题是将数据插入数组。

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

谢谢

最佳答案

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

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();
}

关于java - 如何将数据插入二维多维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55212624/

相关文章:

java - 如何使用 NetBeans 插入后自动刷新绑定(bind)到 Mysql 数据库的 JTable

java - 二维数组列表的排列

c - MPI_Scatter 动态二维数组行导致段错误

php - 在 PHP 中从多个数组创建多维数组

java - 在java中,如何在不同数据类型的数组中创建数组

ios - NSMutableArray 多维覆盖自身

java - 如果滚动一个,则链接两个 TextView 一起滚动

java - 使用 OPC 基金会 Java 堆栈进行浏览

java - 获取铃声 - 英文名称

php - 当键为数字时如何从多维数组中回显单个值?