2011-11-14 92 views
-1

我需要創建一個所有衣服,tuiton,運輸,食物,住房和書籍數組加起來的方法。 例如打印出來有這個樣子將數組中的所有數字相加的方法

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

這真是蹩腳的代碼。首先,正確縮進,其次,你必須在類的頂部聲明你的變量。請做那些事情,以便我們可以做出更好的迴應 –

+1

@DhaivatPandya也許不同的方法更合適?我們並不都是超級Java開發者。而且你不需要在頂部聲明你的屬性,這樣做只是傳統和方便的。儘管我同意最初的代碼是...不太理想,但似乎更好的方法可能會更好。 –

回答

1

這是總結在一個二維數組的所有整數代碼。

int sum = 0; 
for (int[] a : expenseName) { 
    for (int n : a) { 
     sum += n; 
    } 
} 
相關問題