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-08-28
祝你生日快乐!!
在上面的示例中,LocalDate.now() - 返回当前日期
getDayOfMonth() - 返回当前日期
getMonth() - 返回当前月份
在这里,我们使用了if ... else语句来检查当前日期是否匹配生日。如果为true,则打印生日快乐消息。