从文件输入邻接矩阵

时间:2017-03-06 00:00:40

标签: java file file-io java.util.scanner adjacency-matrix

我试图以邻接矩阵的形式将以下文件输入我的程序。

16
-1,1075,716,792,1425,1369,740,802,531,383,811,2211,661,870,999,772
1075,-1,1015,1770,2403,1662,870,1858,941,1426,1437,3026,1486,211,1463,314
716,1015,-1,928,1483,646,390,1085,185,749,530,2034,1377,821,471,772
792,1770,928,-1,633,1089,1111,246,908,409,495,1447,1317,1565,672,1470
1425,2403,1483,633,-1,9999,1630,752,1432,9999,931,814,1938,2198,1016,2103
1369,1662,646,1089,9999,-1,820,1335,832,9999,605,1839,2030,1468,421,1419
740,870,390,1111,1630,820,-1,1224,360,965,690,2197,1480,750,630,705
802,1858,1085,246,752,1335,1224,-1,1021,442,737,1566,1190,1653,918,1558
531,941,185,908,1432,832,360,1021,-1,685,496,2088,1192,736,616,656
383,1426,749,409,9999,9999,965,442,685,-1,738,1858,1938,1221,926,1126
811,1437,530,495,931,605,690,737,496,738,-1,1631,1472,1232,188,1152
2211,3026,2034,1447,814,1839,2197,1566,2088,1858,1631,-1,2752,2824,1563,2744
661,1486,1377,1317,1938,2030,1480,1190,1192,1938,1472,2752,-1,1281,1660,1183
870,211,821,1565,2198,1468,750,1653,736,1221,1232,2824,1281,-1,1269,109
999,1463,471,672,1016,421,630,918,616,926,188,1563,1660,1269,-1,1220
772,314,772,1470,2103,1419,705,1558,656,1126,1152,2744,1183,109,1220,-1

但是,我认为我的逻辑有问题,或者我没有正确使用扫描仪。这是我的代码:

public class Tour 
{
	public static final int N = 16;
	public static final int INF = Integer.MAX_VALUE;
	
	public static void printGrid(int[][] adjMat)
    {
       for(int i = 0; i < 16; i++)
       {
          for(int j = 0; j < 16; j++)
          {
        	 if(adjMat[i][j] == INF)
        		 System.out.printf("%5s", 0);
        	 else
        		 System.out.printf("%5d", adjMat[i][j]);
          }
          System.out.println();
       }
    }
	
	public static void main(String[] args) throws IOException
    {
        File file = new File("american_tour.dat");
        
        Scanner scanner = new Scanner(file);
        
        int[][] adjMat = new int[N][N];
            
            for(int i = 0, n = scanner.nextInt(); i < n; i++)
            	for(int j = 0; j < n; j++)
            		adjMat[i][j] = n;
        
        
        scanner.close();
        printGrid(adjMat);
    }
}

有人可以告诉我如何将文件中的数据正确输入到邻接矩阵中吗?

2 个答案:

答案 0 :(得分:1)

使用扫描仪内置的自定义分隔符支持来改善Mouad的答案:

player = subprocess.Popen(["mpg123", "-Bz", "/media/mp3s/"],.......

答案 1 :(得分:0)

由于您的data不尊重分隔符的特定模式,请尝试以下方式:

public static void main(String[] args) throws FileNotFoundException {

    File file = new File("E:\\american_tour.dat");

    Scanner scanner = new Scanner(file);

    //N in the example equals 16
    int N = scanner.nextInt();

    //skip the first line
    scanner.nextLine();

    int[][] adjMat = new int[N][N];

    for(int i = 0; i < N; i++){

        String[] lines = scanner.nextLine().split(",");

        for (int j=0; j<lines.length; j++) {
            adjMat[i][j] = Integer.parseInt(lines[j]);
        }
    }

    scanner.close();
}