【发布时间】:2014-01-28 05:12:49
【问题描述】:
我真的是 Java 新手,我正在编写一个 Java 程序,它以 mm/dd/yyyy 格式读取日期并以日、年格式打印日期。该程序必须验证年份在 1900 年和 2014 年之间(包括两个限制),并且日期、月份和年份是有效的并且相互一致。如果输入不正确,程序必须显示适当的消息并终止。如果输入正确,输出应以指定格式打印。
例如: 输入日期 2013 年 4 月 30 日 2013 年 4 月 30 日
输入日期 1888 年 1 月 12 日 年份应该在 1900 年到 2014 年之间
我被困在如何限制年份和日期(比如二月只有 28 天),以及如何像上面的例子一样打印出来。我想使用 if else 和 switch 语句来解决这个问题。这是我目前得到的代码,感谢您的帮助。
import java.util.Scanner;
public class Dates {
public static void main(String[] args) {
int month, day, year;
Scanner input = new Scanner(System.in);
System.out.print("Please Enter Date in The Format mm/dd/yyyy : ");
month = input.nextInt();
day = input.nextInt();
year = input.nextInt();
String months = "January February March April May June July August "
+ "September October November December";
String January = months.substring(0,7);
String February = months.substring(8,16);
String March = months.substring(17,22);
String April = months.substring(23,28);
String May = months.substring(29,32);
String June = months.substring(33,37);
String July = months.substring(38,42);
String August = months.substring(43,49);
String September = months.substring(50,59);
String October = months.substring(60,67);
String November = months.substring(68,76);
String December = months.substring(77,85);
if (month == 1) {
months = January;
day = 31;
}
else if (month == 2) {
months = February;
day = 28;
}
else if (month == 3) {
months = March;
day = 31;
}
else if (month == 4) {
months = April;
day = 30;
}
else if (month == 5) {
months = May;
day = 31;
}
else if (month == 6) {
months = June;
day = 30;
}
else if (month == 7) {
months = July;
day = 31;
}
else if (month == 8) {
months = August;
day = 31;
}
else if (month == 9) {
months = September;
day = 30;
}
else if (month == 10) {
months = October;
day = 31;
}
else if (month == 11) {
months = November;
day = 30;
}
else if (month == 12) {
months = December;
day = 31;
}
else {
System.out.print("Invalid Month");
}
if (year >= 1900 || year <= 2014) {
System.out.print(year);
}
else {
System.out.println("Year should be between 1900 and 2014");
}
System.out.println(months + " " + day + ", " + year);
}
}
【问题讨论】:
-
在数字左侧添加零时要小心,因为 Java 会将它们视为 八进制。在您的情况下,它不会影响代码,因为八进制
01等于1以十进制为基数。例如,10 != 010。另外,尝试使用switch语句而不是if-else if结构。 -
您可以使用
split(" ")而不是substring()来分配月份值
标签: java