0

I've been trying to solve this for the past couple of hours with no luck, Here I'm supposed to pass in a multidimensional Array from the main method, to another method that's:

    public static int[] CalcAllRowSums(int[][] a)
{
    int[] p = {a.length}; 
    int x = 0;
    int sum = 0;

    for ( int r = 0; r < a.length; r++ ) {

        for ( int c = 0; c <= a[x].length-1; c++ ) {
            sum += a[x][r];
        }
        p[x] = sum;
    }
    return p;
}

This is how I did it, but when I print out the method from the main method I get the address instead of the actual array.

Thank

0

2 Answers 2

8

You need to use Arrays.toString() to print the string representation of the array.

Sample :

System.out.println("Fourth Question " + 
                    Arrays.toString(TwoD.CalcAllRowSums(array)));

But why are you returning int[] instead of a plain int ?

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

4 Comments

It didn't work, where Do I need to put .toString() ? Here's my main Method: public static void main(String[] args) { System.out.println("Fourth Question " + TwoD.CalcAllRowSums(array)); }
@JackOsborn Wherever you are trying to print your array, if you array is named x. Then use System.out.println(Arrays.toString(x));
Now I'm getting Cannot find Variable Arrays, which is the part I don't actually get
Have you imported it ? import java.util.Arrays; ?
1

There is not such things as a multidimensional array, there's only array of arrays. Each row of your main array contains an array (of possible different length)

First, are you sure you want to store the array length in the array : int[] p = {a.length}; ? If you want to create an array of a.length, just write int[] p = new int[a.length];.

Second, as The New Idiot said, use Arrays.toString(int[]) if you want to have a String reprensentation of your array.

In my example below : System.out.print(rowSums) returns the adresse of the array like [I@4ad6be89 System.out.print(Arrays.toString(rowSums)) returns a string representation like [1,3,42]

Here's an example :

public static int[] sumEachRows(int[][] array) {
    int[] rowSums = new int[array.length];

    for (int x = 0; x < array.length; x++) {
        rowSums[x] = sumOfArray(array[x]);
    }
      System.out.println(rowSums);
      System.out.println(Array.toString(rowSums));
    return rowSums;
}

public static int sumOfArray(int[] array) {
    int sum = 0;
    for(int element: array)
        sum += element; 
    return sum;
}

Comments

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.