java - 矩阵到字符串输出

标签 java string matrix

我目前正在尝试找出如何重新定义我的 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;
     }


}

我知道如何显示它以及如何重新定义 equals 方法,我觉得已经晚了而且我错过了一些愚蠢的东西。给您带来的不便敬请谅解!

编辑:抱歉,我忘记指定它必须显示为二维行 x 列显示。

EDIT2:现在我在重新定义 equals 方法时遇到了麻烦,因为我的作业需要它。我将其重写为:

public boolean equals(Matrix that)
      {
         return this.mat == that.mat;
      }

它仍然输出:

m1 is not equal to m2
m1 is not equal to m3

有什么简单的方法可以解决这个问题吗?

最佳答案

您必须为矩阵中的每个单元格创建一个嵌套循环。

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;
}

至于“等于”方法,我不太清楚其标准是什么。 如果两个矩阵具有相同的行数和列数,您的应用程序是否认为两个矩阵相等?

附注

重写 equal 方法是一个非常好的实践,但重写“hashCode”方法也是更好的实践。 可能与您的应用无关,但很重要。

希望这会有所帮助:)

关于java - 矩阵到字符串输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30497676/

相关文章:

java - Java中的正则表达式不断丢失数据

具有多个查询的 php/mysql

string - 替换 Azure 突触表中的 nvarchar(max)

javascript - 是否有一个快速函数可以将整个矩阵转换为字符串?

C 矩阵和 vector 的动态分配

java - Log4J DailyRollingFileAppender 无法翻转

java - 使用 Integer.MAX_VALUE 条目创建 ArrayBlockingQueue 时出现 OutOfmemory 错误

java - 如何在不使用 split 和 stringtokenizer 的情况下反转 java 字符串中的单词

c++ - Armadillo 矩阵转置

java - 当嵌入式键包含 SQL Server 上的标识列时,Hibernate 插入失败