2011-11-14 4 views
-1

すべての衣服、服飾、輸送、食品、住宅、書籍の配列がその点に合致するメソッドを作成する必要があります。配列内のすべての数値を加算する方法

授業料:$ 3200

食べ物:$ 2600

服:$ 600

例えば、プリントアウトは2011年11月4日のように、この

費のようなものを見て持って

書籍:$ 450

総費用:$ 6850

^これらの数字は、以下の例ではありません。

これはこれは、2次元アレイ内のすべての整数を合計するためのコードである私のコード

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; 
} 
+2

これは本当におかしなコードです。まず、インデントを適切に行います。次に、変数をクラスの先頭に宣言する必要があります。私たちがより良く対応できるように、そのようなことをしてください。 –

+1

@DhaivatPandyaおそらく別のアプローチが適しているでしょうか?私たちはすべてのスーパースターJava開発者ではありません。そして、あなたはトップにあなたのプロパティを宣言する必要はありません。これは通常のやり方で便利です。私は元のコードが最適ではなかったことに同意しますが、より優れたメンター・ツー・アプローチのように思えます。 –

答えて

1

です。

int sum = 0; 
for (int[] a : expenseName) { 
    for (int n : a) { 
     sum += n; 
    } 
} 
関連する問題