【问题标题】:Java - How do I allow users to select a date range and then check that the date range is either 7 or 14 days?Java - 如何允许用户选择日期范围,然后检查日期范围是 7 天还是 14 天?
【发布时间】:2020-03-22 01:10:56
【问题描述】:

我需要先说我对 Java 和一般编程非常陌生,所以会有很多我不理解的概念,所以请尽量保持简单。

p>

基本上,在大学里,我们的任务是创建一个非常简单的酒店预订程序。我们的 OOP 能力没有被评分,所以它只需要在一个班级中并在控制台中完成。

我们需要做的其中一部分是允许用户选择他们逗留的日期范围,我认为这本身相当简单,但他们特别只允许逗留 7 天或 14 天。所以他们不允许停留 3 天或 10 天等。

现在我知道如何使用扫描仪类获取输入,但我觉得获取用户输入的日期是完全不同的野兽。

那么考虑到这一点,我将如何去做呢?

如果这没有意义,请直说,我会尝试进一步澄清。

提前致谢!

【问题讨论】:

  • 您需要:1) 提示用户输入日期2) 将此日期作为字符串读取3) 将字符串转换为 java 中的日期 4) 检查 java 中两个日期之间的持续时间——所有这些都是足够小的任务,我相信你会找到每个问题的答案他们已经在这里了。程序的逻辑由你决定。
  • 坚持让用户使用您决定的格式输入日期。
  • 初学者请提供minimal reproducible example。向我们展示一些代码,您是如何尝试的,然后您可以从那里提出更具体的问题。
  • 只是一个想法:我会询问开始日期,计算两个可能的日期,然后让用户从中选择。

标签: java date input range


【解决方案1】:

来自 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));

在美国语言环境中,这将打印:

以 M/d/yy 格式输入开始日期,例如 10/23/19

例如,在德语语言环境中,输出是不同的:

以 dd.MM.yy 格式输入开始日期,例如 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):

输入停留周数,1 表示出发日期 12/27/19, 2 出发日期为 20 年 1 月 3 日

根据用户输入选择相应的出发日期。

避免使用 Date 和 SimpleDateFormat

其他答案中使用的 DateSimpleDateFormat 类设计不佳,后者出了名的麻烦。它们也早已过时。不要使用它们。相反,我使用的是现代 Java 日期和时间 API java.time。 LocalDate 是一个没有时间的日期,这似乎是您需要的。

链接

【讨论】:

    【解决方案2】:

    我假设您将拥有一个简单的命令行界面。我认为您可以使用扫描仪。事先告诉用户日期需要采用特定格式。例如。可能是 2019 年 2 月 23 日或 23/03/2019 或 03/23/2019。

      private final int SevenDays = 7;
      private final int FourteenDays = 14;
    
      private void checkReservation() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("The Dates should be in the YYYY-MM-DD Format");
        System.out.println("Enter the first date");
        String firstDate = scanner.nextLine();
        try{
          LocalDate startDate = LocalDate.parse(firstDate);
          System.out.println("Enter the Second sate");
          String secondDate = scanner.nextLine();
          LocalDate endDate = LocalDate.parse(secondDate);
    
          checkIfStayAllowed(getDifferenceInDays(startDate, endDate));
        } catch (DateTimeParseException dateParseError){
          dateParseError.printStackTrace();
        }
      }
    
      private void checkIfStayAllowed(int reservation){
        System.out.println(reservation);
        if(reservation == SevenDays){
          System.out.println("Guest is allowed to stay for 7 days");
        } else if (reservation ==FourteenDays){
          System.out.println("Guest is allowed to stay for 14 days");
        }
        // More logic can go here...
        else {
          System.out.println("Guest are only allowed to stay for 7 or 14 days!!!");
        }
      }
    
      private int getDifferenceInDays(LocalDate startDate, LocalDate endDate){
        return endDate.compareTo(startDate);
      }
    

    【讨论】:

    • 请不要教年轻人使用早已过时且臭名昭著的SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API, 和它的DateTimeFormatter 中做得更好。
    • 它似乎也不起作用。在您的示例中,firstDate.compareTo(secondDate) 返回 -1,这似乎与两个日期之间的天数没有任何关系。只有在第一个日期早于第二个日期时,该方法才被记录为返回一个负数,而不是关于哪个负数。
    • @OleV.V.我已经更新了使用 LocalDate 的示例。
    • 谢谢,有一些明确的改进。您有时会正确计算差异,但并非总是如此。我输入2019-12-202020-01-03(14 天)。我得到的输出是1(不正确的天数),然后是Guest are only allowed to stay for 7 or 14 days!!!
    • 输入日期的唯一方法是YYYY-MM-DD;除了少数用户之外,其他任何事情都可能让全世界的所有人都感到困惑。
    【解决方案3】:

    您可以执行以下操作从用户那里获取日期:

    private Date getDateFromUser(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a date in this format dd/mm/yyyy:");
        Date date = new SimpleDateFormat("dd/MM/yyyy").parse(in.next()); //could also use in.nextLine() 
        //which grabs the whole line instead of just up until a space like in.next() does
        return date;
    }
    

    其余的可以随意决定。还要确保关闭扫描仪对象。在尝试创建 Date 对象之前,您可能还需要检查以确保用户输入的内容是正确的。

    【讨论】:

      猜你喜欢
      • 2012-11-06
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 2015-07-03
      相关资源
      最近更新 更多