Indyvette
Indyvette

Reputation: 15

2 Dimensional Arrays

How do I use a one dimensional array to store one dimension of a two dimensional array? This is what I have so far, I just can't get the 1D Array to store anything from the 2D array.

Edit: The loop works exactly as it needs to work. I just need to make 2 one dimensional arrays to store each dimension of the 2 dimensional array.

int[][] tutorData = { // students per day (MTW) per tutor
    {25, 3, 0}, // Amy
    {14, 5, 12}, // John
    {33, 22, 10}, // Nick
    {0, 20, 5}}; // Maria

int numOfDays = tutorData[0].length; // number of days = number of "columns"
int numOfTutors = tutorData.length; // number of tutors = number of "rows"

int[] sumPerDay = {tutorData[i]};
sumPerDay = new int [numOfDays]; // array to store total # of students per day
int[] sumPerTutor = {tutorData[j]};
sumPerTutor = new int[numOfTutors]; // array to store total # of students per tutor

for (int i = 0; i < tutorData.length; i++) {
        for (int j = 0; j < tutorData[i].length; j++) {
            if (j == 0) {
                System.out.println("Tutor " + (i + 1) + " met: " + tutorData[i][j] + "students on (M) ");
            }
            if (j == 1) {
                System.out.println("Tutor " + (i + 1) + " met: " + tutorData[i][j] + "students on (T) ");
            }
            if (j == 2) {
                System.out.println("Tutor " + (i + 1) + " met: " + tutorData[i][j] + "students on (W) ");
            }
            System.out.println();
        }

Upvotes: 1

Views: 141

Answers (2)

mdolbin
mdolbin

Reputation: 936

You need to iterate through your 2d array with nested loop and save the sum of values in each of your columns and rows into 2 different arrays.

int[][] tutorData = { // students per day (MTW) per tutor
                {25, 3, 0}, // Amy
                {14, 5, 12}, // John
                {33, 22, 10}, // Nick
                {0, 20, 5}}; // Maria

int numOfDays = tutorData[0].length; // number of days = number of "columns"
int numOfTutors = tutorData.length; // number of tutors = number of "rows"
int[] sumPerDay = new int [numOfDays]; // array to store total # of students per day
int[] sumPerTutor = new int[numOfTutors]; // array to store total # of students per tutor

for(int i=0; i<numOfDays; i++){
    for(int j=0; j<numOfTutors; j++){
        sumPerDay[i] += tutorData[j][i];
        sumPerTutor[j] += tutorData[j][i];
    }
}

sumPerDay will contain sum of values in each column = total number of students for each day.

sumPerTutor will contain sum of values in each row = total number of students for each tutor.

Upvotes: 0

Axel
Axel

Reputation: 14149

This would be a two-dimensional array because tutorData[i] is an array:

int[] sumPerDay = {tutorData[i]};

Try this:

int[] sumPerDay = tutorData[i];

Upvotes: 3

Related Questions