调用clothing.getLastWornDate()方法报错,需保留原方法签名如何解决?
解决Java作业中saveToFile方法的日期格式化错误
你的代码核心问题出在日期格式化逻辑的误用,和getLastWornDate()方法本身无关,这才是IntelliJ报错的原因。
错误根源
你试图用LocalDate.parse("MM/dd/yyyy")创建日期格式化工具,但LocalDate.parse()的作用是将字符串解析为LocalDate对象,而非生成格式化器。这种错误用法导致后续调用format()时参数类型不匹配,IntelliJ才会误提示修改getLastWornDate()的签名。
修正后的完整代码
/** * 将衣橱中所有衣物信息保存到指定文件。每件衣物单独占一行,格式为: * description,brand,lastWornDate,timesWorn * 日期必须格式化为MM/DD/YYYY。例如,一件描述为"black t-shirt"、品牌为"Gildan"、 * 最后穿着日期为2023年10月25日、穿着次数15次的衣物,文件中对应的行应为: * "black t-shirt,Gildan,10/25/2023,15" * * @param saveFile 保存信息的目标文件 * @return 文件保存成功返回true,否则返回false */ public boolean saveToFile(File saveFile) { // 创建指定格式的日期格式化器 DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); try (FileWriter writer = new FileWriter(saveFile)) { // 用try-with-resources自动关闭资源 for (Clothing clothing : wardrobe) { // 把LocalDate格式化为要求的字符串格式 String formattedDate = dateFormatter.format(clothing.getLastWornDate()); // 去掉逗号后的空格,严格匹配示例格式 String line = String.format("%s,%s,%s,%d%n", clothing.getDescription(), clothing.getBrand(), formattedDate, clothing.getNumOfTimesWorn()); writer.write(line); } return true; } catch (IOException e) { e.printStackTrace(); return false; } }
关键修正点
- 替换错误的
LocalDate初始化,改用DateTimeFormatter作为日期格式化工具 - 用
dateFormatter.format(clothing.getLastWornDate())生成符合要求的日期字符串 - 移除
String.format中逗号后的空格,保证输出格式和示例一致 - 使用
try-with-resources自动关闭FileWriter,避免手动关闭可能的资源泄漏
额外说明
你完全可以保留Clothing类中public LocalDate getLastWornDate()的方法头,这个方法本身没有问题,之前的报错只是格式化逻辑错误导致的连锁提示。
内容的提问来源于stack exchange,提问作者Wremmurg
相关产品推荐
相关产品推荐

