Search code examples
javamatrixtranspose

Transposing a matrix in Java but encountering errors


I have to ensure that I read in a text file(input) and transpose the matrix whereby the rows become columns.

Sample input:

2 4
abcd/
efgh 

(whereby 2 indicates row and 4 indicates column and / indicates new line) and output should look like:

ae/
bf/
cg/
dh

This is my code:

import java.util.*;

public class Transpose {
    private void run() {
        Scanner scan=new Scanner(System.in);
        int Row= scan.nextInt();
        int Col=scan.nextInt();
        char[][] arr=new char[Row][Col];
        for(int i=0;i<Row;i++){
            for(int j=0;j<Col;j++){
                arr[i][j]=scan.next().charAt(0);
            }
        }
        for(int j=0;j<Col;j++){
            for(int i=0;i<Row;i++){
                System.out.print(arr[i][j]);
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        Transpose newTranspose = new Transpose();
        newTranspose.run();
    }
}

However, I am getting the error: programme crashed/producing non-zero exit code Is this a runtime error and how can I go about fixing this.


Solution

  • Try this.

    Scanner scan = new Scanner(System.in);
    int Row = scan.nextInt();
    int Col = scan.nextInt();
    scan.nextLine();    // skip newline.
    char[][] arr = new char[Row][Col];
    for (int i = 0; i < Row; i++) {
        String line = scan.nextLine();
        for (int j = 0; j < Col; j++) {
            arr[i][j] = line.charAt(j);
        }
    }
    for (int j = 0; j < Col; j++) {
        for (int i = 0; i < Row; i++) {
            System.out.print(arr[i][j]);
        }
        System.out.println();
    }
    

    input:

    2 4
    abcd
    efgh
    

    output:

    ae
    bf
    cg
    dh