我目前正在試圖找出如何redifine我的toString方法,以便它將顯示矩陣。下面的代碼..矩陣到字符串輸出
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;
}
}
我知道如何顯示它以及如何redifine equals方法,我覺得這只是晚了,我失去了一些東西愚蠢。對不起,不便之處!
編輯:對不起,我忘了指定它必須顯示爲2維行x列顯示。
編輯2:現在我遇到了重新定義equals方法的麻煩,因爲它是我的任務所必需的。我把它改寫了這個:
public boolean equals(Matrix that)
{
return this.mat == that.mat;
}
,它仍然輸出:
m1 is not equal to m2
m1 is not equal to m3
有沒有簡單的方法來解決這一問題?
你目前的輸出和你想要什麼? – Saif
我的當前輸出只是矩陣的內存地址。我需要它的二維顯示(行x列) – cabb007
等於,你應該檢查行和列國家是否相同,然後你可以檢查數組的elems是否相同。你可以像使用字符串方法一樣使用double for循環來訪問每個元素,看看它們是否相同 – Dude