Search code examples
javaeclipsenewlinefilewriter

I'm unsure why the newline character isn't affecting what's printed


I am writing a simple program to keep track of my fuel consumption. I am trying to figure out why the newline character is not outputting to the file, but the other fields are.

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();

The output to my file ends up being something like this for example:

Miles on trip: 270.67Cost: $33.76Gallons used: 11.567

The desired output to the file I am looking for is:

Miles on trip: 270.67
Cost: $33.76
Gallons used: 11.567


Solution

  • The newline character(s) is (are) platform dependent, and may very well be \r\n on your platform. You can avoid the problem by using printf with the %n special character that gets translated to the proper newline in your platform. As a side effect, it can also help clean up your code and avoid all those string concatinations:

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