首页 > 解决方案 > 为什么我的程序打印值没有相应的打印语句?

问题描述

我试图弄清楚如何从java中的文件中读取一系列值。该文件有多行,每行中的值用逗号分隔。在编写测试程序只是为了弄清楚如何在 Scanner 中使用分隔符时,我遇到了我的程序从文件中打印值的问题。我不知道程序从哪里获取打印所有值的指令。

这就是我的 public static void main 中的内容(在 try 循环中):

File f1 = new File("Data1.txt");
File test = new File("test.txt");
Scanner reader = new Scanner(f1);
Scanner testReader = new Scanner(test);
testReader.useDelimiter(",");

System.out.println("line 18 "+testReader.nextInt());
System.out.println("line 19 "+testReader.nextInt());
System.out.println("line 20 "+testReader.next());
System.out.println("line 21 "+testReader.nextInt());

我正在读取的文件是 test.txt:

4,5,6 
7 
8,9,10

这就是正在打印的内容:

line 18 4
line 19 5
line 20 6
7
8
line 21 9

标签: javajava.util.scannerrepl.it

解决方案


您还需要将换行符添加到分隔符模式中:

testReader.useDelimiter(",|(\r\n)|(\n)");

推荐阅读