Search code examples
javaadjacency-matrix

Reading the values for the graph from text file?


I have a program which will take values from array.

 int graph[][] = new int[][] {{0, 2, 0, 6, 0},
                                {2, 0, 3, 8, 5},
                                {0, 3, 0, 0, 7},
                                {6, 8, 0, 0, 9},
                                {0, 5, 7, 9, 0},
                               };

I have tried changing the inline input to text file input but i am getting type mismatch errors.

Scanner inFile = new Scanner(new File("split_this.txt"));
String s = inFile.nextLine();
int numberOfVertices = Integer.parseInt(s);
while (inFile.hasNext()) {
    s = inFile.nextLine();
    String[] triplet = s.split("[\\|]");
    String[][] tokens = new String[ triplet.length ][];
    for (int i = 0; i < triplet.length; i++){
        tokens[i] = triplet[i].split("[,]");
    }
    for (int z = 0; z < tokens.length; z++){
         for (int i = 0; i < tokens[z].length; i++){
            int graph[][] = tokens[z][i];
         }
    }
}

Please help me.


Solution

  • if you have control on the file format then I would suggest to follow this one which is used in many of the competition problems:

    row col
    val11 val12 val13 ...
    val21 val22 val23 ...
    val31 val32 val33 ...
    ...
    

    example for your case

    5 5
    0 2 0 6 0
    2 0 3 8 5
    0 3 0 0 7
    6 8 0 0 9
    0 5 7 9 0
    

    After this, use Scanner to read the input:

    Scanner scan - new Scanner(file);
    int row = scan.nextInt();
    int col = scan.nextInt();
    int[][] graph = new int[row][col];
    for(int r=0; r<row; r++) {
       for(int c=0; c<col; c++) {
          graph[r][c] = scan.nextInt();
    
      }
    }