1

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.

0

2 Answers 2

2

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+");;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I would expect the full graph table to have 26x26 size. maybe the questioneer can clarify.
@Adder My answer is base on your example, but if you want 26 instead of 8 then use new String[26][] or if you don't want to set the length better use List (check Ganesh Chaitanya answer)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.