[英]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.