我目前正在写我的图论学士论文,并使用 java 扫描器将一个带边的 txt 文件转换成我的 Java 类图。我的 txt 文件如下所示:
1 2 72 3
2 3 15 98
4 7 66 49
5 6 39 48
6 9 87 97
8 13 31 5
整数排序为:源顶点、汇点顶点、成本、容量。
我的代码如下:
Graph graph = new Graph(false);
File f = new File("Filepath");
Scanner in = new Scanner(f);
while (in.hasNextLine())
{
for (int i =1; i<= numberEdges; i++)
{
String s = in.nextLine();
try (Scanner inscan = new Scanner(s)) {
while (inscan.hasNext())
{
int source = inscan.nextInt();
int sink = inscan.nextInt();
double cost =inscan.nextDouble();
double capacity = inscan.nextDouble();
Vertex Source = new Vertex(source);
Vertex Sink = new Vertex(sink);
Edge edge = new Edge(Source,Sink, cost, capacity);
graph.addEdge(edge);
}
}
}
}
in.close();
我尝试扫描字符串中的每一行,然后将字符串扫描到我的变量中。 它总是在 for 循环的第一行抛出一个“NoLineFound”异常,如果我尝试输出这些行,我什么也得不到。但是当我禁用第二个扫描仪并再次尝试时,我得到了输出中的所有行,但最后仍然是“NoLineFound”异常。
我检查了我的 txt 文件,最后一行没有 UTF8 行结尾,但我不知道如何给它一个。
最佳答案
我认为你的问题来自于:
while (in.hasNextLine()){
for (int i =1; i<= numberEdges; i++)
{
首先,迭代是多余的(while
或for
对于阅读每一行来说足够单一,你必须在它们之间做出选择)。
此外,如果您的文件的行数少于 numberEdges
,则会引发 java.util.NoSuchElementException
。
如果文件中的行数是常量,使用for
:
for (int i =1; i<= numberEdges; i++)
删除封闭的 while (in.hasNextLine())
。这不是必需的。 for
已经完成了迭代控制。
如果文件中的行数可能不同,只使用 while
:
while (in.hasNextLine()){
但无论如何,不要同时使用两者。
关于java - 在多行中读取多个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41394271/