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

javaobject oriented programmingprogramming更新于 2024/4/13 19:56:17

在本文中,我们将了解如何检查生日并打印生日快乐消息。通过比较当前日期和给定的生日来检查生日。

下面是相同的演示 −

输入

假设我们的输入是 −

生日日期:7 月 15 日

输出

所需的输出将是 −

今天的日期是 20-12-2021
今天不是我的生日

算法

步骤 1 - 开始
步骤 2 - 声明月份和日期值的变量,即 month_of_birth 和
date_of_birth
步骤 3 - 从用户那里读取所需值/定义值
步骤 4 - 使用 LocalDate.now() 函数获取当前日期并将其存储在变量中。
步骤 5 - 使用 if 循环,分别将当前月份和日期值与输入的日期和月份值进行比较。如果值匹配,则结果为真。
步骤 5- 显示结果
步骤 6- 停止

示例 1

import java.time.LocalDate;
import java.time.Month;
public class HappyBirthday {
   public static void main(String args[]) {
      int date_of_birth = 15;
      Month month_of_birth = Month.JULY;
      System.out.println("The required packages have been imported");
      LocalDate current_date = LocalDate.now();
      System.out.println("Today's Date is " + current_date);
      System.out.println("The birthday is defined as : " +date_of_birth + " " +month_of_birth);
      int date = current_date.getDayOfMonth();
      Month month = current_date.getMonth();
      if(date == date_of_birth && month == month_of_birth) {
         System.out.println("HAPPY BIRTHDAY TO YOU !!");
      } else {
         System.out.println("Your birthday is not today ");
      }
   }
}

输出

The required packages have been imported
Today's Date is 2022-02-09
The birthday is defined as : 15 JULY
Your birthday is not today

示例 2

这里,整数已经被预先定义,并且它的值被访问并显示在控制台上。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Birthday {
   public static void main(String[] args) throws ParseException {
      SimpleDateFormat s = new SimpleDateFormat("MM-dd");
      Date today = s.parse("10-15");
      Date my_birthday_date = s.parse("10-15");
      System.out.println("The birthday date is defined as October 15th" );
      if (today.compareTo(my_birthday_date) == 0) {
         System.out.println("Happy Birthday!!");
      } else {
         System.out.println("Today is not tour birthday");
      }
   }
}

输出

The birthday date is defined as October 15th
Happy Birthday!!

相关文章


有用资源