Java Matrix Array txt文件

时间:2016-03-29 03:00:44

标签: java arrays matrix

所以我有一个文本文件,其上有3个矩阵,如下所示:

2
2 3
5 9

3
3 -2 4
-1 5 2
-3 6 4

4
2 4 5 6
0 3 6 9
0 0 9 8
0 0 0 5

我需要读取此文件并将其放入数组中。从上面可以看出,给出了n x n的数量(2,3,4)。我想知道是否有办法读取这个然后分配一个数组而不读取下面的两次?一旦我读取了txt文件,我将需要对数组进行一些计算并将其打印出来。

public class tester{

  public static void main(String[] args) {
     // TODO Auto-generated method stub         
     try {
         Scanner input = new Scanner(new File(lab2-input.txt"));

         int size = input.nextInt();
         int rowSize = size;
         int columnSize = size;
         int[][] a = new int[size][size];
         System.out.println("Size: " + size);

         while (input.hasNextLine()) {
             for (int i = 0; i < rowSize; i++) {
                 for (int j = 0; j < columnSize; j++) {

                    try{
                     a[i][j] = input.nextInt();

                     }
                    catch (java.util.NoSuchElementException e) {
                        // e.printStackTrace();
                     }
                 }
             }         //print the input matrix
             System.out.println("The input sorted matrix is : ");
             for (int i = 0; i < rowSize; i++) {
                 for (int j = 0; j < columnSize; j++) {

                    System.out.printf("%5d ", a[i][j]);
                 }
                 System.out.println();

             }if(input.hasNextInt()) continue;
         }
     } catch (Exception e) {
         e.printStackTrace();
     }
 }}

我目前得到的输出是:

 Size: 3
 The input sorted matrix is : 
 3    -2     4 
-1     5     2 
-3     6     4 
 The input sorted matrix is : 
 4     2     4 
 5     6     0 
 3     6     9 
 The input sorted matrix is : 
 0     0     9 
 8     0     0 
 0     5     9 

1 个答案:

答案 0 :(得分:1)

这样做你想要的吗?

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {


        // Read input file
        Scanner input = new Scanner(new File("lab2-input.txt"));

        while (input.hasNextInt()) {

            // This should be here to get size of array before getting each array
            int size = input.nextInt();
            int[][] a = new int[size][size];

            for (int i = 0; i < size; i++) {
                for (int j = 0; j < size; j++) {

                    try{
                        a[i][j] = input.nextInt();

                    }
                    catch (java.util.NoSuchElementException e) {
                        // e.printStackTrace();
                    }
                }
            }

            //print the input matrix
            System.out.println("The input sorted matrix is : ");
            for (int i = 0; i < size; i++) {
                for (int j = 0; j < size; j++) {
                    System.out.printf("%5d ", a[i][j]);
                }
                System.out.println();

            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}