简体   繁体   中英

Reading table data into a 2D array in Java

Can anybody please help me with reading a graph data from a file and save the data into a java 2D array or List? I have been struggling

Here is the graph table: 在此处输入图像描述

Here is the code I have so far:

    Scanner matrix = new Scanner(new File("graph_input.txt"));

    String[][] arr = new String[8][];

    while(matrix.hasNextLine()){
        String[] data = matrix.nextLine().split("\\s+");

        for (int i = 0; i < arr.length; i++){
            for (int j = 0; j < arr[i].length; j++){
                arr[i][j] = Arrays.toString(arr[j]);
            }
        }
    }

Thank you very much for any help you can provide.

You have a while and 2 for s. You need only one for

Scanner matrix = new Scanner(new File("graph_input.txt"));

// Base on this you have 8 line in the matrix
String[][] arr = new String[8][];

// Read all 8 lines
for (int i = 0; i < arr.length; i++) {
    // Get the elements of line i
    arr[i] = matrix.nextLine().split("\\s+");;
}

Try the below code:

Scanner matrix = new Scanner(new File("graph_input.txt"));

    ArrayList<ArrayList<String>> matrixArray = new ArrayList<ArrayList<String>>();

    while(matrix.hasNextLine()){
        String[] data = matrix.nextLine().split("\\s+");

        ArrayList<String> innerList = new ArrayList<String>();
        innerList.add(data[0]);
        innerList.add(data[1]);
        matrixArray.add(innerList);
    }

    System.out.println(matrixArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM