Hey! I have matrix class and i want to add, multiply and take transpose of the matrix. for the structure of the code…I made a matrix class with a constructor, basic get methods and the methods to do the operations. Here’s what i have. i’m not sure if i need a constructor or not. I will have an application class that will call the main method. i want to know if so far I’m good with the thought process?
import java.io.*;
import java.util.*;
import java.util.Scanner;
class Matrix {
double[][] element;
int row, col;
Matrix(int a, int b) {
row = a;
col = b;
element = new double[a][b];
}
public double getElement(int a, int b) {
return element[a][b];
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
}
Looks fairly ok so far (although the matrix is declared twice, as the commentor noted). It will definitely be useful to have a constructor in order to instantiate your internal matrix, otherwise you’ll (rather pointlessly) have to do it with another method, and you’d risk calling methods that try to access an uninstantiated matrix (which would not be useful).
Regarding the two matrix declarations: it’s like any other variable. You declare with
double[][] matrixname, then instantiate withmatrixname = new double[a][b](or do both at once if useful). If you dodouble matrixname = new double[a][b]inside the constructor, you’ll be creating a local variable there, which is then lost when the constructor code ends.Also, it might be good to use slightly better method names for clarity. getRow and getCol suggest, to me, that you’d be returning whole rows and whole columns, not the array bounds. Maybe think in terms of width and height?