English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Gestion des exceptions Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

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

Java Examples Comprehensive

在此示例中,我们将学习用生日检查当前日期,并使用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("Today's date: ") + currentDate);
    //Get the 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.");
    }
   }
}

Output1

Today's date: 2020-08-28
Happy birthday to you!!

In the above example,

  • LocalDate.now() - Return the current date

  • getDayOfMonth() - Return the current date

  • getMonth() - Return the current month

Here, we useif ... elseThe statement to check if the current date matches the birthday. If true, then printHappy BirthdayMessage.

Java Examples Comprehensive