用于检查生日并打印生日快乐消息的 Java 程序

要理解此示例,您应该具备以下 Java 编程的知识:

示例:检查生日并返回生日快乐消息

import java.time.LocalDate;
import java.time.Month;

public class Main {
   public static void main(String args[]) {

    // declare variables for birthday
    int birthDate = 23;
    Month birthMonth = Month.SEPTEMBER;

    // get current date
    LocalDate currentDate = LocalDate.now();
    System.out.println("Todays Date: " + currentDate);

    // get current date and month
    int date = currentDate.getDayOfMonth();
    Month month = currentDate.getMonth();

    if(date == birthDate && month == birthMonth) {
      System.out.println("HAPPY BIRTHDAY TO YOU !!");
    }
    else {
      System.out.println("Today is not my birthday.");
    }
   }
}

输出 1

Todays Date: 2020-07-28
HAPPY BIRTHDAY TO YOU !!

在上面的例子中,

  • LocalDate.now() - 返回当前日期
  • getDayOfMonth() - 返回当天
  • getMonth() - 返回当前月份

在这里,我们使用了 if...else 语句来检查当前日期是否与生日匹配。如果为 true ,则打印生日快乐消息。