[英]Java print statement not printing all variables
我正在尝试从文本文件中打印一些数据,文件中的数据将是这样的
user1.txt
1,1412.0
2,345.0
3,500.0
4,234.0
5
**正如有人说文本文件可能包含 \r ** 我将为我的 user1.txt 文件提供链接https://drive.google.com/file/d/1aLCFQhduyt2e3VuBSgR-KJyKgmlz5gO0/view?usp=sharing
代码:
public class Main {
public static void main(String[] args) throws IOException {
// write your code here
File f = new File("D:\\Fit\\user1.txt");
Scanner sc = new Scanner(f);
Scanner csc = new Scanner(f);
sc.useDelimiter("[,\n]");
while (sc.hasNext()){
String d= sc.next();
try { //I only need to print upto 4,234.0 so using a try block
String c = sc.next(); //to skip the last line in text file which is "5"
System.out.println("Day"+d+":"+c+" cal");
}
catch (Exception e){
break;
}
}
}
}
我的问题是,我需要的 output
Day1:1412.0 cal
Day2:345.0 cal
Day3:500.0 cal
Day4:234.0 cal
但是它给出的 output 是
cal
cal
cal
cal
cal
如果我使用System.out.println("Day"+d+":"+c);
它像正常一样给 output
output:
Day1:1412.0
Day2:345.0
Day3:500.0
Day4:234.0
我不知道为什么如果我使用System.out.println("Day"+d+":"+c+" cal")
它只打印“cal”
更改String c = sc.next();
到String c = sc.nextLine().substring(1);
你会得到 output:
Day1:1412.0 cal
Day2:345.0 cal
Day3:500.0 cal
Day4:234.0 cal
正如评论者所观察到的,这几乎可以肯定是一个 \r 问题。
OP 在 Windows 上运行。
Windows 文本文件的行以 \r\n 结尾。
程序指定不包括 \r 的分隔符。
sc.useDelimiter("[,\n]");
该分隔符模式是错误所在的位置。
解决方法:在分隔符模式中包含所有空格
sc.useDelimiter("\s+|,");
意思是“任何字符串的空格,或逗号”。 或者,
sc.useDelimiter("\r?\n|,");
意思是“可选返回后跟换行符或逗号”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.