gpt4 book ai didi

java - 最有效的基本日期验证和转换程序?

转载 作者:行者123 更新时间:2023-12-02 07:08:53 24 4
gpt4 key购买 nike

我计划用 Java 创建一个程序,用于确定输入的年份是否为闰年以及有效日期。我希望将该日期转换为完整的书面名称(4/2/2013 = 2013 年 4 月 2 日),然后确定该日期在一年中的数字(4/2/2013 = 第 92 天)。

有很多程序可以执行其中一种或另一种操作,但我正在学习如何将它们全部结合在一起(如果可能的话)的方法/想法。

要检查闰年,这就是我使用的:

public class LeapYear {
public static void main (String[] args) {
int theYear;
System.out.print("Enter the year: ");
theYear = Console.in.readInt();
if (theYear < 100) {
if (theYear > 40) {
theYear = theYear + 1900;
}
else {
theYear = theYear + 2000;
}
}
if (theYear % 4 == 0) {
if (theYear % 100 != 0) {
System.out.println(theYear + " is a leap year.");
}
else if (theYear % 400 == 0) {
System.out.println(theYear + " is a leap year.");
}
else {
System.out.println(theYear + " is not a leap year.");
}
}
else {
System.out.println(theYear + " is not a leap year.");
}
}

}

我意识到我需要对其进行一些更改以读取一年中的月份和日期,但对于这种情况,我只是检查年份。我怎样才能将输入的相同日期转换为完整的书面姓名?我是否必须创建一个 if 语句,例如:

if (theMonth == 4){
System.out.println("April");
if (theDay == 2){
System.out.print(" 2nd, " + theYear + ".");
}
}

这似乎是很多硬编码工作。我正在尝试限制所需的硬编码量,以便我可以获得类似的内容:

Output:
Valid entry (4/2/2013).
It is April 2nd, 2013.
It is not a leap year.
It is day 92.

如果出现错误,例如无效日期,我希望程序重新提示用户,直到收到有效条目,而不是必须运行程序(在写入“退出”时会结束程序)。

我想我可能只是为主方法(获取日期)创建不同的类,检查它是否是闰年,转换方法,也许还有验证方法。

最佳答案

public void testFormatDate() throws ParseException {
final String[] suffixes =
// 0 1 2 3 4 5 6 7 8 9
{ "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
// 10 11 12 13 14 15 16 17 18 19
"th", "th", "th", "th", "th", "th", "th", "th", "th", "th",
// 20 21 22 23 24 25 26 27 28 29
"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
// 30 31
"th", "st" };
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat odf = new SimpleDateFormat("MMMM"); // Gives month name.
Calendar dayEntered = new GregorianCalendar();
dayEntered.setTime(sdf.parse("04/02/2013"));
System.err.println("You chose date: " + odf.format(dayEntered.getTime()) + " " + dayEntered.get(Calendar.DAY_OF_MONTH) + suffixes[dayEntered.get(Calendar.DAY_OF_MONTH)]
+ " " + dayEntered.get(Calendar.YEAR));
System.err.println("This is " + (((GregorianCalendar)dayEntered).isLeapYear(dayEntered.get(Calendar.YEAR)) ? "" : "not ") + "a leap year.");

System.err.println("This is day: " + dayEntered.get(Calendar.DAY_OF_YEAR));
}

关于java - 最有效的基本日期验证和转换程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15776056/

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