I have variables from a clothes object (sales, cost, price and benefits) that I want to insert into a 2D array. I can create the 4x4 2D array I need with for loops without a problem. My problem is inserting the data into the array.
For example, if I create an object dress(3000, 50, 10, 36000), is there a way for me to insert the 3000, 50, 10 and 36000 into the first row and then keep on going with the 2nd row being pants, 3rd row skirts and so on? I am finding it difficult to put the data into the array without simply going line by line and writing them in brackets one after the other. Is there a more efficient and condensed way to write the code and insert the data into the array?
Thank you
答案 0 :(得分:1)
I would start by creating a clothing class:
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;
}
}
Then you can put all your clothing objects into an array (single dimensional), and iterate through it to fill the 2D array (using the getter methods in the Clothing
class):
//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();
}