Метод, где сложить все числа в массиве - PullRequest
0 голосов
/ 14 ноября 2011

Мне нужно создать метод, в котором вся одежда, одежда, транспорт, еда, жилье и книжные массивы складываются в эту точку. Например, распечатка должна выглядеть примерно так:

Расходы по состоянию на 4 ноября 2011 г .:

Стоимость обучения: $ 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;
}

1 Ответ

1 голос
/ 14 ноября 2011

Это код для суммирования всех целых чисел в 2D-массиве.

int sum = 0;
for (int[] a : expenseName) {
    for (int n : a) {
        sum += n;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...