将矩阵转换为字符串 [英] converting a matrix to string

查看:35
本文介绍了将矩阵转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个矩阵,但不幸的是我被输出困住了.它没有显示矩阵,而是显示如下内容:

I am working on writing a matrix, but unfortunately I am stuck with the output. Instead of showing a matrix, it shows me something like:

实际矩阵是矩阵@512fb063

actual matrix is Matrix@512fb063

我需要将矩阵转换为字符串,以便输出如下所示:

I need to convert the matrix to a string so that the output will look like this:

expected the matrix: 
3   8   72
4   6   60
253 2   1

我写的代码是这样的:

import java.util.Random;
final public class Matrix {
private final int size1;             // number of rows
private final int size2;             // number of columns
private final int[][] data;   // M-by-N array

// create size1-by-size2 matrix of 0's
public Matrix(int size1, int size2) {
    this.size1 = size1;
    this.size2 = size2;
    data = new int[size1][size2];
}

// create matrix based on 2d array
public Matrix(int[][] data) {
    size1 = data.length;
    size2 = data[0].length;
    this.data = new int[size1][size2];
    for (int i = 0; i < size1; i++)
        for (int j = 0; j < size2; j++)
                this.data[i][j] = data[i][j];
}

// creates and returns a random size1-by-size1 matrix with values between 0 and 255
public String toString(int size1, int size2) {
    Matrix A = new Matrix(size1, size2);
    String str = " ";
   final int white = 0;
   final int black = 255;
    for (int i = 0; i < size1; i++)
        for (int j = 0; j < size2; j++)
        {

         A.data[i][j] = white + (int)(Math.random() * ((black ) ));
         str = (A.data[i][j]+"\t"+A.data[i][j+1]);
         if (i==size1 &&j==size2) str = (A.data[i][j]+"\n");

        }

     return str;  

 }

推荐答案

您需要重写 public String toString() 函数.您现在要做的是创建一个名为 String toString(int size1, int size2) 的新函数.

You need to override the public String toString() function. What you are doing now is creating a new function called String toString(int size1, int size2).

编写时未调用您的新函数:

Your new function is not called when writing:

 System.out.println(myMatrix);

你可以这样做:

 System.out.println(myMatrix.toString(2, 2));

或覆盖默认的 toString() 函数.

or override the default toString() function.

所以下面的代码应该可以工作:

So the following code should work:

@Override
public String toString() {
    Matrix A = new Matrix(size1, size2);
    String str = " ";
   final int white = 0;
   final int black = 255;
    for (int i = 0; i < size1; i++)
        for (int j = 0; j < size2; j++)
        {

         A.data[i][j] = white + (int)(Math.random() * ((black ) ));
         str = (A.data[i][j]+"\t"+A.data[i][j+1]);
         if (i==size1 &&j==size2) str = (A.data[i][j]+"\n");

        }

     return str;  

 }

其中 size1size2 是类中的变量.

where size1 and size2 are variables in the class.

这篇关于将矩阵转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆