在回答这个问题之前,我需要先说一下,我对 Java 和编程非常陌生,所以会有很多我不理解的概念,所以请尽量保持简单。
基本上,在大学里我们的任务是创建一个非常简单的酒店预订程序。我们不会根据 OOP 能力进行评分,因此只需在一个类中并在控制台中完成即可。
我们需要做的一部分是允许用户选择停留的日期范围,我认为这本身相当简单,但具体只允许他们停留 7 天或 14 天。所以他们不允许停留3天或10天等。
现在我知道如何使用扫描仪类获取输入,但我觉得获取用户输入的日期是一个完全不同的野兽。
考虑到这一点,我将如何去做呢?
如果这没有意义,请直接说出来,我会尽力进一步澄清。
提前致谢!
最佳答案
来自 java.time 的本地日期
读取用户的开始日期
我建议您要求用户以默认区域设置定义的格式输入日期。用户会很乐意使用他们认为在其文化中常见的格式。为了帮助用户输入正确的格式,首先输出格式和该格式的示例日期。例如:
Locale userLocale = Locale.getDefault(Locale.Category.FORMAT);
String dateFormat = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT, null, IsoChronology.INSTANCE, userLocale);
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(userLocale);
LocalDate exampleDate = LocalDate.of(2019, Month.OCTOBER, 23);
System.out.println("Enter start date in format " + dateFormat
+ ", for example " + exampleDate.format(dateFormatter));
在美国语言环境中,这将打印:
Enter start date in format M/d/yy, for example 10/23/19
例如,在德语区域设置中,输出是不同的:
Enter start date in format dd.MM.yy, for example 23.10.19
现在从用户处读取日期作为字符串,并使用相同的格式化程序对其进行解析。
LocalDate arrivalDate = null;
do {
String inputDateString = yourInputScanner.nextLine();
try {
arrivalDate = LocalDate.parse(inputDateString, dateFormatter);
} catch (DateTimeParseException dtpe) {
System.out.println(inputDateString + " is not in the correct format, please try again");
}
} while (arrivalDate == null);
如果这是一个图形用户界面,人们通常会使用日期选择器而不是文本输入。有一些可用,请使用您的搜索引擎。
从用户处读取日期范围的长度
让用户输入他们想要停留的周数,可以是 1 周,也可以是 2 周。告知他们每种情况的结束日期。
LocalDate departureDate7 = arrivalDate.plusWeeks(1);
LocalDate departureDate14 = arrivalDate.plusWeeks(2);
System.out.println("Enter the number of weeks of the stay,"
+ " 1 for departure date " + departureDate7.format(dateFormatter)
+ ", 2 for departure date " + departureDate14.format(dateFormatter));
示例输出(美国区域设置,输入 12/20/19
):
Enter the number of weeks of the stay, 1 for departure date 12/27/19, 2 for departure date 1/3/20
根据用户输入选择相应的出发日期。
避免日期和 SimpleDateFormat
其他答案中使用的类 Date
和 SimpleDateFormat
设计得很糟糕,后者非常麻烦。它们也早已过时了。不要使用它们。相反,我使用 java.time,现代 Java 日期和时间 API。 LocalDate
是一个没有时间的日期,这似乎正是您在这里所需要的。
链接
- Oracle tutorial: Date Time解释如何使用 java.time。
- 您还可以在my answer to a different question here中找到灵感。 .
关于Java - 如何允许用户选择日期范围,然后检查日期范围是 7 天还是 14 天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59053931/