Reputation: 13
I'm currently trying to figure out how to redifine my toString method so that it will display the matrix. Here's the code..
import java.util.Random;
public class TextLab09st
{
public static void main(String args[])
{
System.out.println("TextLab09\n\n");
Matrix m1 = new Matrix(3,4,1234);
Matrix m2 = new Matrix(3,4,1234);
Matrix m3 = new Matrix(3,4,4321);
System.out.println("Matrix m1\n");
System.out.println(m1+"\n\n");
System.out.println("Matrix m2\n");
System.out.println(m2+"\n\n");
System.out.println("Matrix m3\n");
System.out.println(m3+"\n\n");
if (m1.equals(m2))
System.out.println("m1 is equal to m2\n");
else
System.out.println("m1 is not equal to m2\n");
if (m1.equals(m3))
System.out.println("m1 is equal to m3\n");
else
System.out.println("m1 is not equal to m3\n");
}
}
class Matrix
{
private int rows;
private int cols;
private int mat[][];
public Matrix(int rows, int cols, int seed)
{
this.rows = rows;
this.cols = cols;
mat = new int[rows][cols];
Random rnd = new Random(seed);
for (int r = 0; r < rows; r ++)
for (int c = 0; c < cols; c++)
{
int randomInt = rnd.nextInt(90) + 10;
mat[r][c] = randomInt;
}
}
public String toString()
{
return ("[" + mat + "]");
}
public boolean equals(Matrix that)
{
return this.rows == (that.rows)&&this.cols == that.cols;
}
}
I know how to display it and how to redifine the equals method, I feel like it's just late and I'm missing something silly. Sorry for any inconvience!
EDIT: Sorry, I forgot to specify that it had to be shown as a 2 dimensional row x column display.
EDIT2: Now I'm having trouble redefining the equals method, as it is required for my assignment. I rewrote it to this:
public boolean equals(Matrix that)
{
return this.mat == that.mat;
}
and it still outputs:
m1 is not equal to m2
m1 is not equal to m3
Is there any easy way to fix this?
Upvotes: 1
Views: 2486
Reputation: 69
You'd have to make a nested loop for each cell in your matrix.
public String toString()
{
String str = "";
for (int i = 0 ; i<this.rows ; i ++ ){
for (int j = 0 ; j < this.cols ; j++){
str += mat[i][j]+"\t";
}
str += "\n";
}
return str;
}
As for the "equal" method, I'm not quite sure what is the criteria. Does your application consider two matrixes to be equal if they both have the same number of rows and cols?
P.S.
Overriding the equal method is a very good practice, but it is a better practice to override the "hashCode" method as well. Might not be relevant to your app, but it is important.
Hope that would help :)
Upvotes: 2
Reputation: 100169
Use Arrays.deepToString:
public String toString()
{
return Arrays.deepToString(mat);
}
Upvotes: 1