How would I call the method to the Driver class and be able to print the answer. Read Body for Details

Viewed 8

This is a program to multiply two matrices(with set values) with each other. How would I call the method 'mult' to use in my Driver Class? Would this code even function the way that I want it to? I was thinking that you could make an object and use THAT to call the method but I don't know how. I'm not allowed to use a constructor!(For APCSA)

package tester;
import java.util.Scanner;
import java.util.Arrays;
public class Tester {
    public static void main(String args[]){
        int a[][] = { { 1, 2, -2, 0 },
                    { -3, 4, 7, -2 },
                    { 6, 0, 3, 1 } };
        int b[][] = { { -1, 3 },
                    { 0, 9 },
                    { 1, -1 },
                    {4, -5} };
        System.out.println();//How would I call the method 'mult'?
    }
}
package tester;
public class Tester2 {  
  int[][] mult(int[][] a, int[][] b) {
    int[][] c = new int[a.length][b[0].length];
    int cell = 0;
    for (int row = 0; row < c.length; row++) {
      for (int col = 0; col < c[row].length; col++) {
        for (int i = 0; i < b.length; i++) {
          cell += a[row][i] * b[i][col];
        }
        c[row][col] = cell;
      }
    }
    return c;
  }
}
1 Answers

Your mult method is an instance method of the Tester2 class. The way to call it is to instantiate a Tester2 object and then call mult on the result. The most direct answer to your question is therefore:

(new Tester2()).mult(a, b)

But you talk about not wanting to use a constructor. I'm not sure what that means exactly. If you mean you can't CALL a constructor, then there's no way to use the code you show since the only way to call mult is to first create an instance of Tester2. This will cause Tester2's default constructor to be called. There's no way around that.

The simplest way to avoid instantiating any objects is to make mult a static method. Just do this instead (add the word 'static'):

public class Tester2 {  
  static int[][] mult(int[][] a, int[][] b) {
    ...
    return c;
  }
}

Then you can call mult like this:

Tester2.mult(a, b)
Related