我需要创建一种方法,其中所有衣服,拖鞋,运输,食品,住房和书籍阵列加起来。 例如,打印输出必须看起来像这样
截至2011年11月4日的费用:
学费:3200美元
食物:2600美元
衣服:600美元书籍:450美元
总费用:6850美元
^这些数字是作为一个例子而不是我在下面的那些。
这是我的代码
public class Budget{
///////////////fields////////////////
int clothes[]= {100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210};
int tuition[] = {200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200};
int transportation[]={100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210};
int food[]={80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80};
int housing[]={150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150};
int books[]= {200, 0, 0, 0, 0, 0, 0, 300, 0, 0, 0, 0};
int i=0; // this is arbitrary. Never hard code numbers unless that number is never going to change. in that case you make a variable and define it.
private int expenseName[][] = {clothes, tuition, transportation, food, housing, books};
/////////constructors///////////////
public Budget() {}
public Budget(int name) {this.expenseName[i][i] = name;}
public Budget(int name[], int clothes, int tuition, int transportation, int food, int housing, int books)
{
this.expenseName[i] = name;
this.clothes[i] = clothes;
this.tuition[i] = tuition;
this.transportation[i] = transportation;
this.food[i] = food;
this.housing[i] = housing;
this.books[i] = books;
}
/////////////methods///////////
public int getexpenseName() {return expenseName[i][i];}
public int getclothes() {return clothes[i];}//change the I
public int gettuition() {return tuition[i];}
public int gettransporation() {return transportation[i];}
public int getfood() {return food[i];}
public int gethousing() {return housing[i];}
public int books() {return books[i];}
public void setExpenseName(int name)
{
this.expenseName[i][i] = name;
}
答案 0 :(得分:1)
这是对二维数组中所有整数求和的代码。
int sum = 0;
for (int[] a : expenseName) {
for (int n : a) {
sum += n;
}
}