[英]My program is not printing the string without 'g' and/or 'n'. Why is it so?
[英]Why is my program printing values without a corresponding print statement?
我想弄清楚如何從 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
您還需要將換行符添加到分隔符模式中:
testReader.useDelimiter(",|(\r\n)|(\n)");
您的掃描儀沒有將換行符視為分隔符。 這就是scanner.next()
返回換行符的原因
解決方案是將掃描器配置為以空格和逗號作為分隔符:
testReader.useDelimiter("(,|\\s)");
有關"(,|\\\\s)"
等模式的更多信息,請參見此處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.