2011-11-14 3 views
-1

모든 옷, 뚜통, 수송, 음식, 주거 및 서적 배열이 그 지점까지 합쳐지는 방법을 만들어야합니다.배열의 모든 숫자를 더하는 방법

수업료 : $ 3200

식품 : $ 2600

의류 : $ (600)

을 예를 들어 인쇄 출력 십일 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 아마도 다른 접근 방식이 더 적합할까요? 우리는 모든 슈퍼 스타 자바 개발자가 아닙니다. 그리고 당신은 꼭대기에 당신의 소유물을 선언 할 필요가 없습니다. 단지 그렇게하는 것이 일반적이고 편리합니다. 원본 코드가 하위 수준이라고 동의하는 반면 멘토와 같은 접근 방식이 더 나은 것으로 보입니다. –

답변

1

입니다.

int sum = 0; 
for (int[] a : expenseName) { 
    for (int n : a) { 
     sum += n; 
    } 
} 
관련 문제