Java LocalDate API使用求助:getDayOfWeek方法无法解析问题
问题分析与解决方案
Hey there! Let's break down what's going wrong in your code and fix it step by step.
核心问题定位
你的代码里有两个关键问题导致了报错和逻辑错误:
1. DateUtil类dayOfWeek()方法的语法与类型错误
你写的return LocalDate.of(theDate).getDayOfWeek();存在两个问题:
LocalDate.of()方法需要的是年、月、日数值参数(比如LocalDate.of(2024, 5, 20)),而不是一个已经初始化好的LocalDate对象,这就是IDE提示“cannot resolve method”的根本原因——找不到匹配的方法签名。getDayOfWeek()返回的是DayOfWeek枚举类型,不是字符串,直接返回它无法满足方法要求的String返回值类型。
2. ChallengeThree类dayOfWeek()方法的逻辑偏差
你现在硬编码了创建DateUtil时的日期参数"2000-01-01",但实际上应该使用方法传入的date参数;同时你只是打印结果,没有按照要求返回字符串。
修正后的完整代码
import java.time.LocalDate; import java.time.DayOfWeek; public class ChallengeThree { public static String dayOfWeek(String date) { /** *** Returns a String storing the day of the week in all capital letters of the * given date String * Complete the implementation of the DateUtil class and use it in this function * Arguments * date - a String storing a local date, such as "2000-01-01" * Examples * dayOfWeek("2000-01-01") returns "SATURDAY" */ // ==================================== // Do not change the code before this // CODE1: Write code to return the day of the week of the String date // using the DateUtil class at the bottom of this file DateUtil dateUtil = new DateUtil(date); return dateUtil.dayOfWeek(); // ==================================== // Do not change the code after this } public static void main(String[] args) { String theDayOfWeek = dayOfWeek("2000-01-01"); String expected = "SATURDAY"; // Expected output is true System.out.println(theDayOfWeek.equals(expected)); // 注意:字符串内容比较要用equals(),==比较的是对象引用地址 } } class DateUtil { LocalDate theDate; public DateUtil(String date) { /** * Initialize the theDate field using the String date argument * Arguments * date - a String storing a local date, such as "2000-01-01" */ // ==================================== // Do not change the code before this this.theDate = LocalDate.parse(date); // 简化初始化逻辑,不需要中间变量 // ==================================== // Do not change the code after this } public String dayOfWeek() { /** * Return a String the day of the week represented by theDate */ // ==================================== // Do not change the code before this DayOfWeek dayEnum = this.theDate.getDayOfWeek(); return dayEnum.name(); // name()方法返回枚举的大写字符串名称 // ==================================== // Do not change the code after this } }
解决思路详解
修复DateUtil的
dayOfWeek()方法:- 直接使用已经初始化好的
this.theDate(本身就是LocalDate对象)调用getDayOfWeek(),获取DayOfWeek枚举实例。 - 调用枚举的
name()方法,会返回该枚举常量的大写名称(比如SATURDAY),完美符合题目要求的返回格式。
- 直接使用已经初始化好的
修复ChallengeThree的
dayOfWeek()方法:- 使用方法传入的
date参数创建DateUtil实例,确保逻辑通用性。 - 调用
dateUtil.dayOfWeek()获取结果并返回,满足方法的返回值要求。
- 使用方法传入的
额外小提示:
- 字符串内容比较不要用
==,要用equals()方法——==比较的是对象的内存地址,而equals()才是真正比较字符串的内容。我在main方法里帮你修正了这个细节。
- 字符串内容比较不要用
内容的提问来源于stack exchange,提问作者yaya30001996
相关产品推荐
相关产品推荐

