0

I have searched here and on google but cannot find any information related to printing out a matrix object. I am very new to java and oop.

I can't print out the matrix from the TestMatrix class.

I have created a Matrix class to do this (part of the assignment).

There should be a toString() method to do this, but mine is not working.

I won't be able to see my professor about this until Tuesday. So I would appreciate some help so I can figure it out. Thank you.

This is the TestMatrix class:

double [][] data = new double[][]{ {0.5,1,0}, {1,0.5,0}, {0,0.5,1.25}, {0.5,0.5,0.75}};
    Matrix m3 = new Matrix(data);
    System.out.println("Matrix m3 is a:");
    System.out.println(m3);
    Matrix m3b = new Matrix(data.clone());

This is the Matrix class where I have created the constructor and toString() method:

public class Matrix {

private double[][] data;
private int rows;
private int columns;

public Matrix(double[][] data, int rows, int columns) {
    this.data = new double[rows][columns];
    this.rows = rows;
    this.columns = columns;
}

public Matrix(double[][] data) {
    this.data = new double[rows][columns];

}

public String toString(int rows, int columns) {

    this.data = new double[rows][columns];
    for (int i = 0; i < data.length; i++) {
        for (int j = 0; j < data[i].length; j++) {
            System.out.println(data[i][j]);
        }
    }
    return data[i][j];
}

}

This is the output I'm getting:

Matrix m3 is a: assignment3.Matrix@7852e922

This is the output I'm supposed to be getting:

Matrix m3 is a:

4x3 matrix

0.5 1.0 0.0

1.0 0.5 0.0

0.0 0.5 1.25

0.5 0.5 0.75

1 Answers1

0

You're re-creating your data object in the toString method, which is incorrect. What you likely want to do is loop through that data object and create a string, which you then return.

What you can do is create a string builder, which you append the data to, and then return the string representation of it.

Here's some pseudo code you can use for inspiration:

public String toString() {
  StringBuilder sb = new StringBuilder();

  for(...) {
    for(...) { 
      sb.append(...);
    }
  }

  return sb.toString();
}
Firas Dib
  • 2,743
  • 19
  • 38