我有一个像这样的文本文件:
1 2
3 7
5 8
每行有2个数字。我想用第一个数字和第二个数字做一些不同的事情。我正在尝试扫描文本文件并打印数字以确保我正确扫描它。但是,只有前两个数字显示(1 4),然后出现错误:
"java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:858)
at java.base/java.util.Scanner.next(Scanner.java:1497)
at java.base/java.util.Scanner.nextInt(Scanner.java:2161)
at java.base/java.util.Scanner.nextInt(Scanner.java:2115)
at com.company.SCC.input(SCC.java:30)
at com.company.SCC.<init>(SCC.java:15)
at com.company.Main.main(Main.java:11)"
我不明白问题是什么以及如何逐行扫描文档(我回收了扫描仪的代码,之前它正在运行)。我不确定我做错了什么,任何帮助都会受到赞赏。
try {
String file = "testcase1.txt";
FileReader in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
String s;
int x;
while ((s = br.readLine()) != null) {
Scanner sca = new Scanner(s);
x = sca.nextInt();
graph.addVertex(x);
int y = sca.nextInt();
graph.addAdjvex(x, y);
System.out.println(x + " " + y);
}
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:1)
尝试
try {
File file = new File("testcase1.txt");
Scanner sc = new Scanner(file);
int x, y;
while (sc.hasNextLine()) {
x = sc.nextInt();
y = sc.nextInt()
graph.addVertex(x);
graph.addAdjvex(x, y);
System.out.println(x + " " + y);
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
答案 1 :(得分:1)
try {
File file = new File("testcase1.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int x = sc.nextInt();
int y = sc.nextInt();
sc.nextLine();
graph.addVertex(x);
graph.addAdjvex(x, y);
System.out.println(x + " " + y);
}
sc.close()
} catch (Exception e) {
e.printStackTrace();
}
答案 2 :(得分:0)
也许你应该调用sc.nextLine()来跳转到下一行