我有来自衣服对象的变量(销售、成本、价格和 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/