繁体   English   中英

从文件中读取图形并转换为数组Java

[英]Read graph from file and convert into array Java

我需要从txt文件中读取图形矩阵。 例如

4
0 1 1 0 
1 0 1 0 
1 1 0 1 
0 0 1 0

这是输入文件。 第一个数字是顶点数。 我试过这样的事情:

Scanner sc = new Scanner(file.getAbsolutePath());
int n = sc.nextInt();
int [][] graph = new int [n][n];
for (int x =0; x<n; x++)
    for (int y=0; y<n;y++)
        graph[x][y] = sc.nextInt();

但我得到InputMismatchException 我知道这意味着什么,但我不明白什么是错的。 文件包含int类型字符,我正在使用nextInt() ; 有什么建议么? 也许更简单的方法将矩阵转换为数组? 谢谢你的建议。

您正在为Scanner使用错误的构造函数。 你正在使用这个: https//docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.lang.String) ,它创建了一个字符串为的Scanner输入流。

将构造函数更改为new Scanner(new FileReader(file.getAbsolutePath()))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM