简体   繁体   English

为什么我的程序打印值没有相应的打印语句?

[英]Why is my program printing values without a corresponding print statement?

I am trying to figure out how to read in a series of values from a file in java.我想弄清楚如何从 java 中的文件中读取一系列值。 The file has multiple lines and the values are separated with commas in each line.该文件有多行,每行中的值用逗号分隔。 While writing a test program just to figure out how to use a delimiter with Scanner I ran into an issue with my program printing values from the file.在编写测试程序只是为了弄清楚如何在 Scanner 中使用分隔符时,我遇到了我的程序从文件打印值的问题。 I don't know where the program is getting instructions to print all the values from.我不知道程序从哪里获取打印所有值的指令。

This is what is in my public static void main (inside a try loop):这是我的 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());

The file I am reading from is test.txt:我正在读取的文件是 test.txt:

4,5,6 
7 
8,9,10

And this is what is being printed:这是正在打印的内容:

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

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

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

Your scanner is not seeing the linefeed characters as delimiters.您的扫描仪没有将换行符视为分隔符。 This is the reason why the linefeed characters get returned by scanner.next()这就是scanner.next()返回换行符的原因

Solution is to configure the scanner to have space and comma as delimiters:解决方案是将扫描器配置为以空格和逗号作为分隔符:

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

See here for more info on patterns like "(,|\\\\s)" .有关"(,|\\\\s)"等模式的更多信息,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的程序没有打印没有'g'和/或'n'的字符串。 为什么会这样呢? - My program is not printing the string without 'g' and/or 'n'. Why is it so? 为什么我的程序关闭而不打印堆栈跟踪或异常? - Why does my program close without printing a stack trace, or exception? 为什么我的偶数和奇数打印程序只打印奇数次? - Why does my even and odd printing program print just print odd many times? Java程序未打印我的所有打印语句 - Java program not printing all of my print statements for循环后的打印语句不打印,为什么? - The print statement after for loop is not printing, why? 如何在没有打印语句的情况下运行多线程程序? - How to run a multithreaded program without a print statement? 为什么我的程序在输入后没有打印出来? - Why is my program not printing out after the input? 为什么我的程序打印“ null”而不是字符串? - Why is my program printing “null” instead of the string? 为什么我的程序打印出异常语句会不断给用户带来不好的输入? - Why does my program print out the exception statement endlessly give bad user input? 为什么我的 main 中的打印输出语句不显示在我的 fillArray 方法中输入的值? - Why isn't the print out statement in my main displaying the values that were entered in my fillArray method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM