【发布时间】:2019-03-05 02:40:34
【问题描述】:
您好,我需要 Java 方面的帮助。因为我一直在尝试使用扫描仪从文件中输出行,但我没有成功。这是文件内容的样子:
4
5
3->1->25
1->0->12
2->0->-5
0->1->0
2->1->7
我尝试做的第一件事是从第三行开始输出信息,效果很好。这是代码:
public static void main(String[] args) throws Exception {
Scanner scanner = null;
BufferedReader in = null;
String line = null;
try{
scanner = new Scanner(new BufferedReader(new FileReader("graphe.txt")));
//in = new BufferedReader(new FileReader("graphe.txt"));
scanner.useDelimiter("->");
while (scanner.hasNextLine()){
int value = scanner.nextInt();
scanner.skip(scanner.delimiter());
int value2 = scanner.nextInt();
scanner.skip(scanner.delimiter());
String value3 = scanner.nextLine();
int value3Int = Integer.parseInt(value3);
System.out.println(value + " - > " + value2 + " cost " + value3Int);
}
}catch (IOException e){
e.printStackTrace();
}finally {
if (scanner != null){
scanner.close();
}
}
}
}
但是当我插入值 4 和(第一行和第二行)时,我试图弄清楚如何处理它。我做的第一件事是尝试使用 if 条件来查看分隔符是否存在,如果不存在,我将其打印出来:
public static void main(String[] args) throws Exception {
Scanner scanner = null;
BufferedReader in = null;
String line = null;
try{
scanner = new Scanner(new BufferedReader(new FileReader("graphe.txt")));
//in = new BufferedReader(new FileReader("graphe.txt"));
scanner.useDelimiter("->");
while (scanner.hasNextLine()){
String find = scanner.nextLine();
if (!(find.contains("->"))){
System.out.println(find);
}
else {
int value = scanner.nextInt();
scanner.skip(scanner.delimiter());
int value2 = scanner.nextInt();
scanner.skip(scanner.delimiter());
String value3 = scanner.nextLine();
int value3Int = Integer.parseInt(value3);
System.out.println(value + " - > " + value2 + " cost " + value3Int);
}
}
}catch (IOException e){
e.printStackTrace();
}finally {
if (scanner != null){
scanner.close();
}
}
}
}
但它并没有像预期的那样工作,我有这个错误作为输出
4
5
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
1 - > 0 cost 12
at java.base/java.util.Scanner.next(Scanner.java:1594)
0 - > 1 cost 0
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at com.tpTG.LectureGrapheMatrice.main(LectureGrapheMatrice.java:25)
Process finished with exit code 1
请我知道我可以处理它,但我一直在思考,但我不知道该怎么做。请帮忙谢谢。
【问题讨论】:
-
你要忽略4和5还是别的什么?
-
不,我想打印所有这些行
-
你不知道这些单数行有多少,对吧?
-
对不起?请我不明白你想说什么。但我要说的是我想打印出文件中的所有行
-
一旦您阅读了带有
scanner.nextLine()的行并确定它有一个分隔符,您就开始调用scanner.next()和scanner.skip()来尝试剖析它。但此时,scanner.next()和scanner.skip()现在正在从 next 行读取。