Home > Software design >  save txt file to 2D matrix
save txt file to 2D matrix

Time:10-09

i am beginner in java programming and i have no idea, how to save txt information to 2D matrix. The next operation what i am going to do is transpose matrix etc.

My code:

 File text = new File("/matrix.txt");

    System.out.print("\Path to file: ");
    Scanner sc = new Scanner(System.in);
    String m = sc.nextLine();

    BufferedReader br = new BufferedReader(new FileReader("m));
    String st;

    System.out.println("matrix");

    while ((st = br.readLine()) != null)
        System.out.println(st);

the output is for example:

matrix
1 0 0 0 0 1 1 
0 1 0 0 1 0 0 
0 0 1 0 1 1 1
0 0 0 1 0 0 1 

I need to the same output, bud in matrix. Thanks

I've tried:

Scanner sc = new Scanner(new BufferedReader(new FileReader("/matrix.txt")));
            int rows = 4;
            int columns = 7;
            int [][] myArray = new int[rows][columns];
            while(sc.hasNextLine()) {
                for (int i=0; i<myArray.length; i  ) {
                    String[] line = sc.nextLine().trim().split(" ");
                    for (int j=0; j<line.length; j  ) {
                        myArray[i][j] = Integer.parseInt(line[j]);
                    }
                }
            }
            System.out.println(Arrays.deepToString(myArray));

but the output is not what i would expected

[[1, 0, 0, 0, 1, 1, 1], [0, 1, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 1, 1, 0, 1]]

yes, it is corret but the graphical output is different. Does exists another choice?

CodePudding user response:

Try something like this

System.out.println("[");
for (int i = 0; i < myArray.length; i  ) {
    System.out.print("  [ ");
    for (int j = 0; j < myArray[i].length; j  ) {
        System.out.print(myArray[i][j]   " ");
    }
    System.out.println("]");
}
System.out.println("]");
  • Related