【问题标题】:Why is my program printing values without a corresponding print statement?为什么我的程序打印值没有相应的打印语句?
【发布时间】:2020-06-18 10:39:02
【问题描述】:

我试图弄清楚如何从 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

【问题讨论】:

  • 因为文件包含,6\n7\n8, - 注意逗号的位置。

标签: java java.util.scanner repl.it


【解决方案1】:

您的扫描仪没有将换行符视为分隔符。这就是scanner.next()返回换行符的原因

解决方案是将扫描仪配置为以空格和逗号作为分隔符:

testReader.useDelimiter("(,|\\s)");

有关"(,|\\s)"等模式的更多信息,请参阅here

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    猜你喜欢
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 2021-05-20
    • 1970-01-01
    • 2022-10-17
    相关资源
    最近更新 更多