I am working on a Java assignment for school. In this method, I am trying to save to a file as described by assignment, but I am getting an error when calling clothing.getLastWornDate() and am lost as to how to correct it.
/**
* Saves all of pieces of clothing in this wardrobe to the designated file. Each piece of
clothing
* in the Wardrobe is written on its own line, formatted as
description,brand,lastWornDate,timesWorn.
* The date must be formatted MM/DD/YYYY.For example, lets say a piece of clothing had a
description
* of "black t-shirt", brand of "Gildan", a lastWorn date of October 25th, 2023, and has been
worn
* 15 times. Then the line in the text file is "black t-shirt,Gildan,10/25/2023,15"\n.
*
* Parameters:
* saveFile - the File that the information should be written to
* Returns:
* true if the file saved successfully, false otherwise
* @param saveFile
* @return
*/
public boolean saveToFile(File saveFile) {
try {
FileWriter writer = new FileWriter(saveFile);
LocalDate dateFormat = LocalDate.parse(("MM/dd/yyyy"));
for (Clothing clothing : wardrobe) {
String formattedDate = dateFormat.format(clothing.getLastWornDate());
String line = String.format("%s, %s, %s, %d\n", clothing.getDescription(), clothing.getBrand(),
formattedDate, clothing.getNumOfTimesWorn());
writer.write(line);
}
writer.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
Declaration of Clothing.getLastWornDate:
public LocalDate getLastWornDate() {
return lastWornDate;
}
I am lost as to how to fix this. Intellij is telling me to change the method header for getLastWornDate, but assignment write up is specific as to leave the header as public LocalDate getLastWornDate(). Any suggestions would be appreciated.
Invalid code.
You cannot parse a formatting pattern. I suspect you want to use
DateTimeFormatterhere.Also invalid code.
You defined
dateFormatas aLocalDaterather than as aDateTimeFormatter. Theformatmethod onLocalDatetakes a parameter of typeDateTimeFormatter, but you are passing aLocalDateobject.Programming by intuition is risky business. I suggest you instead try programming by documentation. Carefully read the Javadoc before coding. Also, search Stack Overflow as date-time handling in Java has been addressed many times already.
Tip: Compile and run your code often. Write the least code you can to be able to run successfully before adding more code.
Tip: Never store nor exchange date-time values textually in a localized format. Use only standard ISO 8601 formats for that. Conveniently, the java.time classes use ISO 8601 formats by default when parsing/generating text.
Revise your code to be something similar to this: