gpt4 book ai didi

java - 从文件输入邻接矩阵

转载 作者:行者123 更新时间:2023-12-01 08:46:37 26 4
gpt4 key购买 nike

我正在尝试以邻接矩阵的形式将以下文件输入到我的程序中。

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

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

最佳答案

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

Scanner scanner = new Scanner(file);
scanner.useDelimiter("[\\s,]+");

int N = scanner.nextInt();
int[][] adjMat = new int[N][N];

for(int i=0; i < N; i++) {
for (int j=0; j < N; j++) {
adjMat[i][j] = scanner.nextInt();
}
}

scanner.close();

关于java - 从文件输入邻接矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42615563/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com