0

Sorry guys, I'm a beginner in Java and I was wondering if I could get some help.

import java.util.Scanner;
import java.util. Arrays;

public class Matrices_Lab
{
    public static int sumMat( int[][] matty )
    {
      //code

}

   public static void main(String[] args) 
   {
       int[][] mat = {{2,3,4},{55,66,77},{22,11}};

       System.out.println( sumMat( mat ) );

   }
}

the //code part is what I have to fill in. This is what I have so far but it is not working.

 int[] finished_array;
       for(int i=0; i<matty.length;i++){
           for(int j=0; j<matty.length;j++){
             int[] temp+=  matty[j][i];

             finished_array=temp;

Can someone help me out? How do I fill in the function to successfully make it work?

lolwuwunoo
  • 81
  • 2
  • In the second for loop, you need to use i index: `for(int j=0; j – B.J. Smegma Aug 18 '14 at 15:22
  • Related / Possible Duplicate of http://stackoverflow.com/questions/15638550/finding-sum-of-two-dimensional-array-java – Unihedron Aug 25 '14 at 04:48
  • Since you have some responses below that seem to answer your question, please consider marking one of them as ‘Accepted’ by clicking on the tickmark below their vote count. This shows which answer helped you most, and it assigns reputation points to the author of the answer (and to you!). It's part of this site's idea to identify good questions and answers through upvotes and acceptance of answers. – jub0bs Dec 02 '14 at 15:09

1 Answers1

0

Get your first matrix, and your second matrix. Think, how do you add up matrices...you need the same (row, column) point for each of them. Then, loop through each point in the matrix and do it.

Rows and Columns should be given, use your own values

NOTE: This obviously works for 2 matrices. Make a function and just keep looping through making all the matrices you want.

Ex.

private void makeMatrix()
{
    while("condition")
       //code below for matrix
}

       //First matrix
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               a[i][j] = foo.nextInt();
           }
       }
       //Second Matrix
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               b[i][j] = foo.nextInt();
           }
       }
       int[][] c = new int[rows][columns];
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               c[i][j] = a[i][j] + b[i][j];
           }
       }
       //Sum of the 2 matrixes
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               System.out.print(c[i][j] + " ");
           }
           System.out.println();
Adam
  • 2,422
  • 18
  • 29