开发者

java 2d array arithmetic

开发者 https://www.devze.com 2023-03-08 02:48 出处:网络
Guys, I am struggling studying for exam with the 2d array of past exam paper. I have to write a method

Guys, I am struggling studying for exam with the 2d array of past exam paper. I have to write a method

sumr static (int[][] v)

that returns a 2d array consisting of 2 rows and the entries of the first row sums of v and the second row is the same of the first row of v. Eg:

a = {{2,3,3}, {1,3}, {1,2}}

the method returns 2d array

b = {{8,4,3},{2,3,3}}

I first try to make my method return a 2d array, but I was having the error illegal start of expression, now I have the following code, but the last element does not print and the elements a printed all in in line, not in a matrix way... Please guys help me, my exam is tomorrow.

public class Sum
{

    //  int[][] a = {{2, 3, 3开发者_StackOverflow中文版}, {1, 3}, {1, 2}};


    public void sumr(int[][] v)
    {
        for(int rows = 0; rows < v.length; rows++){
            for(int columns = 0; columns < v.length; columns++){
                int result = v[rows][columns];
                System.out.print(result + " ");
                //return [][] result;
            }
        }
    }

    public int getCount(int[][] Array)
    {
        int result = 0; //temp location to store current count
        for (int i = 0;i <= Array.length -1;i++){//loop around first array
            //get the length of all the arrays in the first array
            //and add them onto the temp variable
            result += Array[i].length; 
        }
        return result;
    }

}


In the outer loop (after the inner loop) include:

System.out.println(); // go to next line!

And check against the inner-array length!!

int[] innerArray = v[rows];
for(int columns = 0; columns < innerArray.length; columns++){

It is:

public void sumr(int[][] v)
{
    for(int rows = 0; rows < v.length; rows++){
        int[] innerArray = v[rows];
        for(int columns = 0; columns < innerArray.length; columns++){
            int result = v[rows][columns];
            System.out.print(result + " ");
            //return [][] result;
        }
        System.out.println(); // go to next line!
    }
}

Once you can iterate:

You must construct a two-items array:

1st item: "summed array" 2nd item: the same as v[0]

You must build that result.

You must build the 1st item iterating over v. Like you are trying to do. For each row (outer loop) you will iterate over the row and sum its values. So after processing each row (after the inner loop) you will have the summed value. That value must be placed into the "summed array".

Next you can build directly the result array, assigning the built sum to its first place and v[0] to the second place.

But I'm not writing code yet to let you do it ;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消