[英]Reading multiple integers in multiple lines
我目前正在用图论编写我的学士论文,并使用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();
我尝试扫描String中的每一行,然后将String扫描到我的变量中。 它总是在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 8流:
Files
.lines(f.toPath())
.map(l ->Arrays.stream(l.split(" ")).mapToDouble(Double::parseDouble).toArray())
.map(a->new Edge(new Vertex((int)a[0]), new Vertex((int)a[1]), a[2], a[3]))
.forEach(graph::addEdge);
您正在阅读nextLine()
在一个循环中的一个检查后hasNextLine()
您需要在每次读取后执行检查,以避免“NoLineFound”异常。
看起来嵌套循环完全没必要。 您可以逐行读取文件,忽略空行,并在不事先了解其具有的边数的情况下构建图形:
Graph graph = new Graph(false);
File f = new File("Filepath");
Scanner in = new Scanner(f);
while (in.hasNextLine()) {
String s = in.nextLine();
try (Scanner inscan = new Scanner(s)) {
if (!inscan.hasNext()) {
continue; // Ignore empty lines
}
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();
只需在阅读后执行检查以避免“NoLineFound”异常。
您可以使用以下代码扫描文件:
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.