dlawil2049
dlawil2049

Reputation: 61

How to create toString method for 2d array

I'm writing a program for matrix computations and it has to include a toString method to show the matrix. This is what I have so far, but I'm not sure if I'm doing it right.

Upvotes: 1

Views: 351

Answers (2)

dreamcrash
dreamcrash

Reputation: 51623

With Java 8, you can do it very elegantly:

    public String toString() {
        return Stream.of(info).map(Arrays::toString).collect(Collectors.joining("\n"));
    }

A simple toString method (without using streams) for a matrix can be something like:

public String toString() {
    StringBuilder str = new StringBuilder(); 
    for (int i = 0; i < info.length; i++){
       for (int j = 0; j < info[i].length; j++)
           str.append(info[i][j]).append(" ");
       str.append("\n");
    }
    return str.toString();
}

You have several mistakes in your code.

In your constructor, you are missing two parameters (i.e., r and c). However, you do not really need them; you can simply use the matrix passed as a parameter to figure out the info matrix size.

// Constructor 
public Matrix(double[][] info) {
    this.info = new double[info.length][info[0].length];
    for (int i = 0; i < info.length; i++) {
        for (int j = 0; j < info[0].length; j++) {
            this.info[i][j] = info[i][j];
        }
    }
}

The constructor is meant to be invoked from outside of your class:

//calling the constructor ?
Matrix second = new Matrix(new double[][]{{2, 8},{-4, 6},{0, -2}});

for instance:

class Main {  
  public static void main(String args[]) { 
     Matrix second = new Matrix(new double[][]{{2, 8},{-4, 6},{0, -2}}); 
  } 
}

Finally, you do not need variables to store the matrix sizes

 this.a = r;
 this.b = c;

that information can be retrieved in Java from the matrix itself.

Upvotes: 2

Krzysztof Witkowski
Krzysztof Witkowski

Reputation: 155

If you put this into a main method it works fine:

public static void main(String[] arg){
        //calling the constructor ?
        Matrix second = new Matrix(new double[][]{{2, 8}, {-4, 6}, {0, -2}});
        for(double[] i: second.info){
            for(double j: i){
                System.out.println(j);
            }
        }
    }

Remember only that in the second costructor you should write this:

public Matrix(double[][] info) {

        this.info = info;
}

because the parameter is info not the size of the matrix.

Upvotes: 0

Related Questions