1

I need to preface this question by saying that I am incredibly new to Java and programming in general so there are going to be a lot of concepts I don't understand so please try to keep it as simple as possible.

Basically, in college we've been tasked with creating a really simple hotel booking program. We're not being graded on our OOP abilities so it just has to be in one class and done in the console.

A part of it we need to do is allowing the user to select a date range for their stay, which by itself would be fairly simple I think but they are specifically only allowed to stay 7 days or 14 days. So they're not allowed to stay 3 days or 10 days etc.

Now I know how to take input with the scanner class but I feel like taking user-inputted dates is a whole different beast.

So with that in mind how would I go about doing this?

If that doesn't make sense just say and I'll try to clarify further.

Thanks in advance!

Blackbath
  • 19
  • 8
  • 4
    You need to: **1)** prompt the user to enter a date **2)** read in this date as a String **3)** convert a String to a date in java **4)** check the duration between two dates in java -- All of these are small enough tasks and I'm sure you will find the answer to each of them on here already. The logic of the program is up to you. – sleepToken Nov 26 '19 at 15:16
  • 3
    Insist that the user enters dates using a format that YOU decide. – user1717259 Nov 26 '19 at 15:18
  • Please come up with [mcve] for starters. Show us some code, how are you trying to do it, then from there you can come up with more specific questions. – Sergei Sirik Nov 26 '19 at 15:27
  • 3
    Just a thought: I would ask for the start date, calculate the two possible dates and let the user choose from these. – glglgl Nov 27 '19 at 10:54
  • 1
    Start from [the Oracle Java date time tutorial](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Nov 27 '19 at 22:11

3 Answers3

2

LocalDate from java.time

Read the start date from the user

I suggest that you ask the user to input the date in a format defined by the default locale. Users will be happy to use a format that they recognize as common in their culture. To help the user type the correct format, first output both the format and an example date in that format. For example:

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

In US locale this will print:

Enter start date in format M/d/yy, for example 10/23/19

In German locale, for example, the output is different:

Enter start date in format dd.MM.yy, for example 23.10.19

Now read the date as a string from the user and parse it using the same formatter.

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

If this was for a graphical user interface, one would typically use a date picker rather than textual input. There are some available, use your search engine.

Read the length of the date range from the user

Have the user input the number of weeks they want to stay, either 1 or 2. Inform them of the end date in each case.

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

Example output (US locale, input 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

Based on the user input select the corresponding departure date.

Avoid Date and SimpleDateFormat

The classes Date and SimpleDateFormat used in the other answers are poorly designed, the latter notoriously troublesome. They are also long outdated. Don’t use them. Instead I am using java.time, the modern Java date and time API. A LocalDate is a date without time of day, which seems to be what you need here.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

I presume that you are going to have a simple command line interface. I think you can should use the scanner. Tell the use before hand that the dates need to be in a particular format. E.G. It could be 23rd Feb,2019 or 23/03/2019 or 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);
  }
Vinnie
  • 452
  • 5
  • 24
  • 4
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Nov 27 '19 at 19:34
  • It also doesn’t seem to work. In your example `firstDate.compareTo(secondDate)` returns -1, which doesn’t seem to have anything to do with the number of days between the two dates. The method is only documented to return a negative number if the first date is earlier than the second, nothing about which negative number. – Ole V.V. Nov 27 '19 at 19:57
  • @OleV.V. I have update the example which would use LocalDate. – Vinnie Nov 28 '19 at 16:24
  • 1
    Thanks, there are some definite improvements. You are getting the calculation of the difference right sometimes, not always. I enter `2019-12-20` and `2020-01-03` (14 days). The output I get is `1` (incorrect number of days) and then `Guest are only allowed to stay for 7 or 14 days!!!`. – Ole V.V. Nov 28 '19 at 17:45
  • The only way to enter dates is [YYYY-MM-DD](https://en.wikipedia.org/wiki/ISO_8601#Calendar_dates); anything else will likely confuse all but a handful of users across the World. – Neil Nov 28 '19 at 17:59
0

You could do something like this to get the date from the user:

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;
}

The rest can be decided however you would like. Also make sure to close the scanner object. You might also need to check to make sure what the user entered is okay before you try the creation of the Date object.

Devon
  • 160
  • 1
  • 12