【问题标题】:I'm unsure why the newline character isn't affecting what's printed [duplicate]我不确定为什么换行符不会影响打印的内容[重复]
【发布时间】:2018-03-18 16:36:04
【问题描述】:

我正在编写一个简单的程序来跟踪我的油耗。我想弄清楚为什么换行符没有输出 到文件,但其他字段是。

PrintWriter fuelLog = new PrintWriter(new FileWriter("FuelLog.txt", true));
fuelLog.println("New Trip");
miles = JOptionPane.showInputDialog("Please enter trip miles...");
dollars = JOptionPane.showInputDialog("Please enter cost to refuel...");
gallons = JOptionPane.showInputDialog("Enter the gallons used on the trip...");

fuelLog.println("Miles on trip: " + miles + "\n" + 
                "Cost: $" + dollars + "\n" + 
                "Gallons used: " + gallons);
fuelLog.close();

我的文件的输出最终是这样的,例如:

旅行里程:270.67 成本:33.76 美元使用加仑:11.567

我要查找的文件的所需输出是:

行程里程:270.67
成本:33.76 美元
使用加仑数:11.567

【问题讨论】:

    标签: java eclipse newline filewriter


    【解决方案1】:

    换行符取决于平台,很可能是您平台上的\r\n。您可以通过使用带有%n 特殊字符的printf 来避免该问题,该特殊字符会在您的平台中转换为正确的换行符。作为副作用,它还可以帮助清理您的代码并避免所有这些字符串连接:

    fuelLog.printf("Miles on trip: %s%n" + 
                   "Cost: $%s%n" + 
                   "Gallons used: %s%n", miles, dollars, gallons);
    

    【讨论】:

    • 好的。你的方法解决了我遇到的问题。我有一个关于 %s 字符的问题。该角色是否会获取我拥有的字符串并插入它们?我不清楚那个具体的角色。
    • @RyanEdwards 是的,确实 - 详情请参阅 docs.oracle.com/javase/8/docs/api/java/util/…
    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 2014-12-15
    • 2011-04-21
    相关资源
    最近更新 更多