Home > Mobile >  Calling static method in main part
Calling static method in main part

Time:08-08

How can I call a method in the main method ?

public class Sum extends ConsoleProgram {
    public void run() {
        int[][] array = {{32, 4, 14, 65, 23, 6},
                        {4, 2, 53, 31, 765, 34},
                        {64235, 23, 522, 124, 42}};
    }

    public static int sumRow(int[][] array, int row) {
        int sum = 0;
        for(int col = 0; col < array[row].length; col  ) {
             sum  = array[row][col];
        }
        return sum;
    }
}

I used this option

public void run() {
    int[][] array = {{32, 4, 14, 65, 23, 6},
                    {4, 2, 53, 31, 765, 34},
                    {64235, 23, 522, 124, 42}};
    sumRow(); // and this way System.out.println(sumRow);
    
}

Expected result:

144
889
64946⏎

Actual result:

You forgot to print something.

CodePudding user response:

public static int sumRow(int[][] array, int row)

this requires a matrix int[][] array and an integer int row as inputs.
then it outputs an integer static int as output.
Therefore when you call the function you must write it like so:

sumrow(array, row);

And print it out like so:

System.out.println(sumrow(array, row));

As pointed out by @k314159.

To get the output of all three arrays inside the matrix you would have to:

System.out.println(sumrow(array, 0));
System.out.println(sumrow(array, 1));
System.out.println(sumrow(array, 2));

And this should output the sum of all three arrays in the matrix.

Also I would like to point out that int[][] is a matrix and not an array, so it would be more "correct" to declare it like so:

public class Sum extends ConsoleProgram {
    public void run() {
        int[][] matrix = {{32, 4, 14, 65, 23, 6},
                        {4, 2, 53, 31, 765, 34},
                        {64235, 23, 522, 124, 42}};
    }

    public static int sumRow(int[][] matrix, int row) {
        int sum = 0;
        for(int col = 0; col < matrix[row].length; col  ) {
             sum  = matrix[row][col];
        }
        return sum;
    }
}
  •  Tags:  
  • java
  • Related