Java程序检查生日并打印生日快乐消息
要理解这个示例,你需要了解以下 Java 编程 主题:
示例:检查生日并返回生日快乐消息
import java.time.LocalDate;
import java.time.Month;
public class Main {
public static void main(String args[]) {
// 声明生日变量
int birthDate = 23;
Month birthMonth = Month.SEPTEMBER;
// 获取当前日期
LocalDate currentDate = LocalDate.now();
System.out.println("今天的日期: " + currentDate);
// 获取当前的日期和月份
int date = currentDate.getDayOfMonth();
Month month = currentDate.getMonth();
if(date == birthDate && month == birthMonth) {
System.out.println("生日快乐!!");
}
else {
System.out.println("今天不是我的生日。");
}
}
}
输出 1
今天的日期: 2020-07-28
生日快乐!!
在上面的示例中,
- LocalDate.now() - 返回当前日期
- getDayOfMonth() - 返回当前日
- getMonth() - 返回当前月份
这里,我们使用了 if...else 语句来检查当前日期是否与生日相匹配。如果为 true
,则打印 生日快乐 消息。