rafiaTech
rafiaTech

Reputation: 433

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: enter image description here

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.

Upvotes: 1

Views: 541

Answers (2)

Butiri Dan
Butiri Dan

Reputation: 1772

You have a while and 2 fors. 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+");;
}

Upvotes: 2

Ganesh chaitanya
Ganesh chaitanya

Reputation: 658

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);

Upvotes: 1

Related Questions