Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何正确地将对象显示为字符串_Java_Tostring - Fatal编程技术网

Java 如何正确地将对象显示为字符串

Java 如何正确地将对象显示为字符串,java,tostring,Java,Tostring,我正在编写这段代码,希望能打印出一个矩阵,但结果就是这样 Matrix@2c78bc3b Matrix@2a8ddc4c 这是一个代码示例: public class Matrix { public static int rows; public static int colms;//columns public static int[][] numbers; public Matrix(int[][] numbers) { numb

我正在编写这段代码,希望能打印出一个矩阵,但结果就是这样
Matrix@2c78bc3b Matrix@2a8ddc4c

这是一个代码示例:

public class Matrix
{

    public static int rows;
    public static int colms;//columns
    public static int[][] numbers;

    public Matrix(int[][] numbers)
    {

        numbers = new int[rows][colms];

    }


    public static boolean isSquareMatrix(Matrix m)
    {
        //rows = numbers.length;
        //colms = numbers[0].length;

        if(rows == colms)
           return true;
        else
            return false;
    }

    public static Matrix getTranspose(Matrix trans)
    {
       trans = new Matrix(numbers);

        for(int i =0; i < rows; i++)
        {
            for(int j = 0; j < colms; j++)
            {
                trans.numbers[i][j] = numbers[j][i];
            }
        }
        return trans;
    }



    public static void main(String[] args)
    {
        int[][] m1 = new int[][]{{1,4}, {5,3}};
        Matrix Mat = new Matrix(m1);

        System.out.print(Mat);
        System.out.print(getTranspose(Mat));

    }
}
公共类矩阵
{
公共静态int行;
公共静态int colms;//列
公共静态int[][]数字;
公共矩阵(int[][]个数字)
{
数字=新整数[行][列];
}
公共静态布尔isSquareMatrix(矩阵m)
{
//行=数字。长度;
//colms=数字[0]。长度;
如果(行==列)
返回true;
其他的
返回false;
}
公共静态矩阵getTranspose(矩阵传输)
{
trans=新矩阵(数字);
对于(int i=0;i
您需要以一种有意义的方式实现
toString()

这个
toString()
(如下)可能适合调试,但如果您将其用于实际用户输出,它将非常难看和混乱。实际的解决方案可能会以某种复杂的方式使用a来生成整齐的表格行和列

基于您的代码的一些其他建议:

  • 建议不要单独存储行/列大小。或只需使用
    .length
    ,并在需要时提供访问器方法
  • 在方法args中使用
    final
    ,它将消除与上面类似的错误,在构造函数中使用别名
    number
  • 使用实例,而不是静态的
  • 偏执狂是程序员的生活方式:我还修改了我的代码,对提供的
    int[][]
    数组进行
    deepCopy
    ,否则会出现引用泄漏,如果调用方代码后来修改了它们传入的
    int[][
    ,那么
    Matrix
    类将无法强制执行自己的不变量

  • 出于习惯,我将我的
    矩阵
    设置为不可变(请参见
    最终私人号码[][]
    )。这是一个很好的实践,除非您为可变实现提供了一个很好的理由(对于矩阵中的性能原因,这并不奇怪)

下面是一些改进的代码:

public final class Matrix
{
    final private int[][] numbers;

    // note the final, which would find a bug in your cited code above...
    public Matrix(final int[][] numbers)
    {   
        // by enforcing these assumptions / invariants here, you don't need to deal 
        // with checking them in other parts of the code.  This is long enough that you might 
        // factor it out into a private void sanityCheck() method, which could be 
        // applied elsewhere when there are non-trivial mutations of the internal state

        if (numbers == null || numbers.length == 0) 
          throw new NullPointerException("Matrix can't have null contents or zero rows");
        final int columns = numbers[0].length;
        if (columns == 0) 
          throw new IllegalArgumentException("Matrix can't have zero columns");
        for (int i =1; i < numbers.length; i++) {
          if (numbers[i] == null) 
             throw new NullPointerException("Matrix can't have null row "+i);
          if (numbers[i].length != columns) 
             throw new IllegalArgumentException("Matrix can't have differing row lengths!");
        }
        this.numbers = deepCopy(numbers);
    }

    public boolean isSquareMatrix() { return rowCount() == columnCount(); }
    public int rowCount() { return numbers.length; }
    public int columnCount() {return numbers[0].length; }

    private static int[][] deepCopy(final int[][] source)
    {
       // note we ignore error cases that don't apply because of 
       // invariants in the constructor:
       assert(source != null); assert(source.length != 0);
       assert(source[0] != null); assert(source[0].length != 0);
       int[][] target = new int[source.length][source[0].length];
       for (int i = 0; i < source.length; i++) 
          target[i] = Arrays.copyOf(source[i],source[i].length);
       return target;
    }

  public Matrix getTranspose()
  {

    int[][] trans = new int[columnCount()][rowCount()];

    for (int i = 0; i < rowCount(); i++)
      for (int j = 0; j < columnCount(); j++)
        trans[i][j] = getValue(j, i);
    return new Matrix(trans);
  }

  @Override
  public String toString()
  {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < numbers.length; i++) 
    { 
      for (int j = 0; j < numbers[i].length; j++) 
        sb.append(' ').append(numbers[i][j]);
      sb.append('\n');
    }
    return sb.toString();
  }

  public static void main(String[] args)
  {
    final int[][] m1 = new int[][] { { 1, 4 }, { 5, 3 } };
    Matrix mat = new Matrix(m1);
    System.out.print(mat);
    System.out.print(mat.getTranspose());
  }
}
公共最终类矩阵
{
最终专用整数[][]编号;
//注意最后一个,它会在上面引用的代码中发现一个bug。。。
公共矩阵(最终整数[][]个)
{   
//通过在这里强制执行这些假设/不变量,您无需处理
//在代码的其他部分检查它们。这足够长,您可以
//将其分解为一个私有的void sanityCheck()方法,该方法可以是
//当内部状态发生非平凡的突变时,应用于其他地方
if(numbers==null | | numbers.length==0)
抛出新的NullPointerException(“矩阵不能有空内容或零行”);
最终整数列=数字[0]。长度;
如果(列==0)
抛出新的IllegalArgumentException(“矩阵不能有零列”);
对于(int i=1;i
您没有为矩阵类定义
toString
方法,因此当您尝试打印矩阵时,您会看到默认的
toString
方法的结果,该方法打印对象的类和唯一id

System.out.print(Mat);
它将调用Matrix类的toString方法

所以,如果你想打印你的矩阵,你必须重写toString方法

@Override
public String toString() {
    // create here a String representation of your matrix
    // ie: String myString = "1 0 0 1\n0 1 1 1\n...";
    return "String representation of my matrix";
}

要在可以打印时显示
矩阵
类对象,必须在类中定义
toString
方法

代码中的另一个错误是,您没有设置
的值。所以当你这么做的时候

numbers = new int[rows][colms];
在构造函数中,
的默认值始终为

public String toString() {
    return Arrays.deepToString(numbers);
}