Question

Hey so for my assignment we're working with class and clients. For the class my transpose method isn't printing my matrix the way it should be. Here is my method:

  public Matrix transpose(){
    Matrix a= this;
    for(int r=0; r<size;r++){
      for(int c=0;c<size;c++){
        a.table[r][c]=this.table[c][r];
      }
    }
    return a;
  }

and here is the client calling the method:

case 5:
      first.init(LOW,UP);
      System.out.println("The original matrix is:");
      first.print();
      result=first.transpose();
      System.out.println("The resulting matrix is:");
      result.print();
      break;

and the print method if you need to see it:

  public void print(){
    for(int r=0;r<size;r++){
      for(int c=0;c<size;c++)
        System.out.printf("%5d",table[r][c]);
      System.out.println();
    }
  }

but the output isn't right:

The original matrix is:
    9    7    1
    7    1    1
    5    5    7
The resulting matrix is:
    9    7    5
    7    1    5
    5    5    7

The rows and columns aren't printing the right numbers after the call. Any help to fix this would be great!

Was it helpful?

Solution

The problem is that in your transpose method, both Matrix a and this refer to the same object. So you can try

1. Matrix a= new Matrix(...);//... since it depends on your constructor

or

You can loop the lower triangle of matrix and swap the element [i][j] with [j][i] since currently you are 'trying to' swap twice.

So make sure you don't swap twice and you are swapping correctly

OTHER TIPS

This solution uses a new array to hold the transposed values:

public static void main(String[] args) {
    int[][] matrix = new int[][] {
        { 9, 7, 1 },
        { 7, 1, 1 },
        { 5, 5, 7 }
     };

    int[][] transposed = new int[3][3];
    for (int c=0; c<3; c++) for (int r=0; r<3; r++) transposed[c][r] = matrix[r][c];

    for (int r=0; r<3; r++) {
        for (int c=0; c<3; c++) {
            System.out.print(transposed[r][c] + "  ");
        }
        System.out.println();
    };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top