Java 打印语句不打印所有变量

时间:2021-05-25 11:55:29

标签: java

我正在尝试从文本文件中打印一些数据,文件中的数据将是这样的

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;
           }
        }

    }
}

我的问题是,我需要的输出

Day1:1412.0 cal  
Day2:345.0 cal  
Day3:500.0 cal  
Day4:234.0 cal 

但它给出的输出是

 cal    
 cal    
 cal    
 cal    
 cal    

如果我使用 System.out.println("Day"+d+":"+c); 它会像正常一样提供输出
输出:

Day1:1412.0    
Day2:345.0    
Day3:500.0    
Day4:234.0  

我不知道为什么它只打印“cal”,如果我使用 System.out.println("Day"+d+":"+c+" cal")

2 个答案:

答案 0 :(得分:0)

String c = sc.next(); 改为 String c = sc.nextLine().substring(1); 你会得到输出:

Day1:1412.0 cal
Day2:345.0 cal
Day3:500.0 cal
Day4:234.0 cal

答案 1 :(得分:0)

正如评论者所观察到的,这几乎肯定是一个 \r 问题。

OP 在 Windows 上运行。

Windows 文本文件的行以 \r\n 结尾。

程序指定不包含 \r 的分隔符。

sc.useDelimiter("[,\n]");

该分隔符模式是错误所在。

解决方法:在分隔符模式中包含所有空格

sc.useDelimiter("\s+|,");

意思是“任何空格字符串或逗号”。或者,

sc.useDelimiter("\r?\n|,");

意思是“可选的返回后跟换行符或逗号”。