gpt4 book ai didi

java - JAVA程序根据出生日期和当前日期计算人的年龄

转载 作者:行者123 更新时间:2023-12-01 19:32:25 24 4
gpt4 key购买 nike

此代码将从用户处接受当前日期、月份和年份;以及他们的出生日期、出生月份、出生年份。它输出人的年龄(以年、月和日为单位)。我编写的代码完成了它的工作。我已经在互联网上的一个网站上进行了交叉检查。我想知道:

How do I implement the Date class in Java to get the current Date, Month and Year? Will I be better off with Swing or AWT kits, if I want to make a GUI?

import java.util.*;
class AgeCalc
{
static int[] MonthDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
public static void Input(int cd, int cm, int cy)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Birth Date");
int bd = scan.nextShort();
System.out.println("Enter Birth Month");
int bm = scan.nextShort();
System.out.println("Enter Birth Year");
int by = scan.nextShort();
int fnd = (DaysofMidYears(by, cy)) + Birth_CurrYearDays(bd, bm, by, cd, cm, cy);
int y = fnd / 365;
int m = (fnd - (y * 365)) / 30;
int d = (fnd - (y * 365) - (m * 30));
System.out.println("No. of Days: "+d);
System.out.println("No. of Months: "+m);
System.out.println("No. of Years: "+y);
}
public static boolean LeapYearTest(int y)
{
boolean lys =
( ((y % 400) == 0) ? true
: ((y % 10) == 0) ? false
: ((y % 4) == 0) ? true
: false );
return lys;
}
public static int DaysofMidYears(int by, int cy)
{
int dmy = 0;
for
(int i = (by + 1); i <= (cy - 1); i++)
{
dmy += 365;
if
((LeapYearTest(i)) == true)
{
dmy += 1;
}
}
return dmy;
}
public static int InitialDaysofYear(int d, int m, int y)
{
int id = d;
for
(int i = 1; i <= (m - 1); i++)
{
id += (MonthDays[i - 1]);
}
if
(((LeapYearTest(y)) == true) && (m > 2))
{
id += 1;
}
return id;
}
public static int Birth_CurrYearDays(int bd, int bm, int by, int cd, int cm, int cy)
{
int bcyd = 0;
bcyd += (InitialDaysofYear(cd, cm, cy));
bcyd += (365 - (InitialDaysofYear(bd, bm, by)));
if
((LeapYearTest(by)) == true)
{
bcyd += 1;
}
return bcyd;
}
}

最佳答案

我们不再使用java.util.Datejava.sql.Date类。它们在几年前就被 JSR 310 中定义的现代 java.time 类所取代。

对于没有时间和时区的仅日期值,请使用 LocalDate

LocalDate birthDate = LocalDate.of(y, m, d);

对于耗时或年龄,请使用 Period类。

LocalDate today = LocalDate.now();
Period age = Period.between(birthDate, today);
long years = age.getYears();

关于java - JAVA程序根据出生日期和当前日期计算人的年龄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59223205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com