0

My goal for this program is to create a 2D-array ratings whose size is specified by the first two arguments from the command line. args[0] would represent the number of rows r and arg[1] would represent the number of columns c. The next arguments that follow would all be used to fill in the array. So if the command-line argument was 3 2 5 2 3 3 4 1. I would hope that the array would be 3 rows by 2 columns. The value 5 would be in ratings[0][0], the value 2 would be in ratings[0][1], the value 3 would be in ratings[1][0], etc. After that, I want to compute the sum of each column. So column 0 would be 12 and column 1 would be 6 in this scenario.

public static void main(String[] args) {
    int r = Integer.parseInt(args[0]);
    int c = Integer.parseInt(args[1]);
    int[][] ratings = new int[r][c];
    int z = 2;
    int y = 3;
    int x = 0;
    int counting = 0;
    int sum = 0;
    for (int rows = 0; rows < ratings.length; rows++ ) {
        for (int column = 0; column < ratings[c].length; column++){
            ratings[rows][column] = Integer.parseInt(args[z]);
            sum += ratings[rows][column];
            z++;
        }
        System.out.println(sum);
        sum = 0;
    }
    //System.out.println(movieRating);
}

This is my attempt at summing the columns but this right now just sums 5 and 2, 3 and 3, 4 and 1. I want the columns not the rows to be summed but do not know how to fix it. Thank you

6
  • 1
    Your first for loop fills the columns, not the rows, so the second row does the vice versa. That maybe is the source of the confusion. Is it right? If so, then I would make another array traversal and sum up the columns in that traversal. But I'm not sure if that is the right way to do that. Commented Oct 10, 2020 at 5:24
  • 1
    You either need an array of column sums, or you need to do the summing in a separate step after you've built the array. Commented Oct 10, 2020 at 5:28
  • I want the columns not the rows to be summed but do not know how to fix it I don't understand what you mean by this. Sum up all rows or sum up all column is same thing Commented Oct 10, 2020 at 5:28
  • @Eklavya The OP wants the sum for each column. Notice the sum = 0; instruction inside the outer for loop. Commented Oct 10, 2020 at 5:36
  • @Patrick Did you mean the sum for each column of every row separately? How can you just assume from sum = 0; ? Commented Oct 10, 2020 at 5:39

3 Answers 3

0

You seem to be adding the values to the 2D array correctly. What you're missing is an additional nested loop to print out the column totals:

for (int i = 0; i < ratings[c].length; i++) {
   int colSum = 0;
   for (int j = 0; j < ratings.length; j++) {
      colSum += ratings[j][i];
   }
   System.out.println(colSum);
}

Add that where you currently have that //System.out.println(movieRating); line. Since you were adding the numbers to the array row-wise, you need to flip the for loops to be able to sum the columns.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey! Thanks so much for the information. I was hoping that you may be able to help me with one last problem. I have pieced together a bunch of the solutions from this thread and now my code looks like pastebin.com/QncDa8NH - It works great! I only want to make one change, which is I want the end result of the program to display the column with the highset sum, and if there is no highest sum to display the lowest sum. Is that going to be possible within the for loop? I have already tried playing around with it to no avail. I cannot figure out how to store the sum as a variable % compar
@zambonideen What I would do is declare a new HashMap with HashMap<Integer, Integer> sumMap = new HashMap<>();. Then as you calculate each column sum within the for loop, use sumMap.put(columnIndex, columnSum) to put each sum into sumMap with the column index as the key. Then once they've all been calculated, loop through the HashMap and find the key (column index) corresponding to the max value. There's an example of it here: stackoverflow.com/questions/5911174/…
0

Things you did right

You correctly initialized the ratings 2D-array with the values given on the command line. Let me re-write this below without your attempt at computing the columns' sum. Note that I renamed the variables so that the indices used in the for loop are single letter variable.

public static void main(String[] args) {
    int rows = Integer.parseInt(args[0]);
    int columns = Integer.parseInt(args[1]);
    int[][] ratings = new int[rows][columns];
    int argIndex = 2;
    
    for (int r = 0; r < ratings.length; r++ ) {
        for (int c = 0; column < ratings[r].length; c++){
            ratings[r][c] = Integer.parseInt(args[argIndex]);
            argIndex++;
        }
    }
}

Thing you didn't get right

The ratings array is filled row by row. In the code you posted, you compute in variable sum the sum of the elements inserted in the same row. This is the reason why it doesn't print the results you expected.

To compute the sum of each columns, I would recommend you create a new array in which to store this result. Integrating it with the code above:

public static void main(String[] args) {
    int rows = Integer.parseInt(args[0]);
    int columns = Integer.parseInt(args[1]);
    int[][] ratings = new int[rows][columns];
    int[] columnSums = new int[columns];
    int argIndex = 2;
    
    for (int r = 0; r < ratings.length; r++ ) {
        for (int c = 0; column < ratings[r].length; c++){
            ratings[r][c] = Integer.parseInt(args[argIndex]);
            columnSums[c] += ratings[r][c];
            argIndex++;
        }
    }

    // array columnSums contains your results
}

4 Comments

Hey Patrick, I really appreciate the response and the detailed notes. However, I somehow am more confused than before. I tried copying the code you sent and it was meant with a bunch of errors. I think too many variable names got moved, and now I am having trouble following what is happening. Would you mind reposting the code with comments, or more clear variable names? I tried to get that to run and was unable too.
Yeah I noticed too. I think I just fixed it. Could you try again? I had forgotten to rename z in some places.
Hey! Thanks so much for the information. I was hoping that you may be able to help me with one last problem. I have pieced together a bunch of the solutions from this thread and now my code looks like pastebin.com/QncDa8NH - It works great! I only want to make one change, which is I want the end result of the program to display the column with the highset sum, and if there is no highest sum to display the lowest sum. Is that going to be possible within the for loop? I have already tried playing around with it to no avail. I cannot figure out how to store the sum as a variable % compar
Identifying the column with the highest sum can be done from the columnSums array. However this is outside the scope of this question. Try and look for "finding max value in array". I am sure you will find plenty of solutions. Here is a question with an answer which you can adapt to your problem. If you still have a problem, it is best to ask a new question.
0

I have changed your original code with a simpler version. Let me know if you have problems understanding the solution.

public static void main(String[] args)
{
    int row = Integer.parseInt(args[0]);
    int col = Integer.parseInt(args[1]);
    
    int arrayLength = row * col;            // use a single dimension array, for simplicity
    int[] ratings = new int[arrayLength];   // the array size is based on the rows and columns
    
    // add data to the 'ratings' array
    // This is not actually needed because the conversion can be done directly when the columns are summed up
    for(int i = 0; i < arrayLength; i++)
    {
        ratings[i] = Integer.parseInt(args[i + 2]);
    }
    
    // sum up the columns using the % operator
    int[] result = new int[col];
    for(int i = 0; i < arrayLength; i++)
    {
        result[i % col] += ratings[i];
    }
    
    // print result
    for(int i = 0; i < result.length; i++)
    {
        System.out.println(String.format("Movie %d rating is %d", i, result[i]));
    }
}

PS: you are missing the validation around the String to int conversion and checks around the correctness of the user input

2 Comments

Hey! Thanks so much for the information. I was hoping that you may be able to help me with one last problem. I have pieced together a bunch of the solutions from this thread and now my code looks like pastebin.com/QncDa8NH - It works great! I only want to make one change, which is I want the end result of the program to display the column with the highset sum, and if there is no highest sum to display the lowest sum. Is that going to be possible within the for loop? I have already tried playing around with it to no avail. I cannot figure out how to store the sum as a variable % compar
I don't really understand what you mean by highest and lowest sum but if you need to do that it's really easy. You just need to browse again through the result array and find the highest and lowest values. You can't do that while suming the values into the result array because you only get partial 'highs' and partial 'lows'. Here is an example of how you can do that: beginnersbook.com/2014/07/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.