1

I'm completely brand new to programming and Java so excuse any stupid mistakes and really awful code (I have no clue how to order/format). I've been given a task to make an inventory of videos which has three functions: list, rent and check. I have an ArrayList which holds the current inventory of videos available. Under the check function I want to be able to convert the returndate string into a Date and then compare this to today's date. If the returndate and today's date are equal I want to return a message saying: "Video is due today" and if the returndate has passed (is earlier than today's date) I want to return a message saying "Video is overdue".

I've been researching how to convert strings into dates and vice versa and have been trying all day to use this and more to try and make it work but I just can't seem to get it to work. I know there are many similar questions like this that have been asked and answered but I've tried following them and it's not working. Any help would be really appreciated. As I said before I'm a total newbie so excuse any stupidity.

Whole program code:

import java.text.DateFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.*;

class InventoryRow {
private String name;
private String type;
private Character availability;
private String returndate;

public InventoryRow(String name, String type, Character availability, String returndate) {
    this.name = name;
    this.type = type;
    this.availability = availability;
    this.returndate = returndate;
}

public String getReturndate() {
    return returndate;
}

public void setReturndate(String returndate) {
    this.returndate = returndate;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public Character getAvailability() {
    return availability;
}

public void setAvailability(Character availability) {
    this.availability = availability;
}

public String toString() {
    return name + "   " + type + "   " + availability + "   " + returndate;
}
}

public class InventorySort {

public static void main(String[] args) throws ParseException {
    List<InventoryRow> videos = new ArrayList<InventoryRow>();

    videos.add(new InventoryRow("Casablanca", "Old", 'Y', null));
    videos.add(new InventoryRow("Jurassic Park", "Regular", 'N', "2015-07-30"));
    videos.add(new InventoryRow("2012", "Regular", 'Y', null));
    videos.add(new InventoryRow("Ant-Man", "New", 'Y', null));

    LocalDate dateReturn = LocalDate.now().plusDays(3);

    LocalDate dateToday = LocalDate.now();

    Scanner input = new Scanner(System.in);

    // Output the prompt
    System.out.println("Do you want to list (l), rent (r) or check (c)?");

    // Wait for the user to enter a line of text
    String line = input.nextLine();

    // List, rent and check functions
    // List function
    if (line.equals("l")) {
        // //////////////////////////// Sort function
        Collections.sort(videos, new Comparator<InventoryRow>() {
            public int compare(InventoryRow o1, InventoryRow o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        for (InventoryRow inventory : videos) {
            System.out.println(inventory);
        }
        // /////////////////////////// Rent function
    } else if (line.equals("r")) {
        System.out.println("Which video would you like to rent?");
        String line2 = input.nextLine();
        // /////////////////////////// Search through ArrayList
        boolean foundIt = false;
        for (InventoryRow ir : videos) {
            if (line2.equals(ir.getName()) && ir.getAvailability() == 'Y') {
                foundIt = true;
                break;
            }
        }
        if (foundIt) {
            System.out.println("Video available to rent! Would you like to rent this video?");
            String line3 = input.nextLine();
            if (line3.equals("Yes")) {
                System.out.println("You have rented this video until " + dateReturn + ".");
                for (InventoryRow ir : videos) {
                    if (ir != null && line2.equals(ir.getName())) {
                        ir.setAvailability('N');
                        ir.setReturndate(dateReturn.toString());
                        // //////////////// Just to test if this works
                        for (InventoryRow inventory : videos) {
                            System.out.println(inventory);
                        }
                    }
                }
            } else {
                System.out.println("You have not rented this video.");
            }

        } else {
            System.out.println("Video unavailable to rent.");
        }
        // /////////////////////////// Check function
    } else if (line.equals("c")) {
        System.out.println("Which video would you like to check is in the inventory?");
        String line4 = input.nextLine();
        // /////////////////////////// Search through ArrayList
        boolean foundIt = false;
        for (InventoryRow ir : videos) {
            if (line4.equals(ir.getName())) {
                foundIt = true;
                break;
            }
        }
        if (foundIt) {
            System.out.println("Video found!");
            for (InventoryRow ir : videos) {
                LocalDate returnDate = LocalDate.parse(ir.getReturndate());
                if (line4.equals(ir.getName()) && ir.getAvailability() == 'N' && returnDate.isEqual(dateToday)) {
                    System.out.println("Video due for return today.");
                } else if (line4.equals(ir.getName()) && ir.getAvailability() == 'N'
                        && returnDate.isBefore(dateToday)) {
                    System.out.println("Video is overdue!");
                } else if (line4.equals(ir.getName()) && ir.getAvailability() == 'N') {
                    System.out.println("Video is due for return on: " + ir.getReturndate());

                }
            }
        } else {
            System.out.println("Video not found. Please see the inventory below.");
            Collections.sort(videos, new Comparator<InventoryRow>() {
                public int compare(InventoryRow o1, InventoryRow o2) {
                    return o1.getName().compareTo(o2.getName());
                }
            });
            for (InventoryRow inventory : videos) {
                System.out.println(inventory);
            }
        }
        // /////////////////////////// If anything else is entered
    } else {
        System.out.println("The only options are to list (l), rent (r) or check (c).");
    }

}
}

This is the bit that isn't working and I don't know why:

if (foundIt) {
            System.out.println("Video found!");
            for (InventoryRow ir : videos) {
                LocalDate returnDate = LocalDate.parse(ir.getReturndate());
                if (line4.equals(ir.getName()) && ir.getAvailability() == 'N' && returnDate.isEqual(dateToday)) {
                    System.out.println("Video due for return today.");
                } else if (line4.equals(ir.getName()) && ir.getAvailability() == 'N'
                        && returnDate.isBefore(dateToday)) {
                    System.out.println("Video is overdue!");
                } else if (line4.equals(ir.getName()) && ir.getAvailability() == 'N') {
                    System.out.println("Video is due for return on: " + ir.getReturndate());

                }
            }

This is the error message I get:

Exception in thread "main" java.lang.NullPointerException: text
at java.util.Objects.requireNonNull(Objects.java:228)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1846)
at java.time.LocalDate.parse(LocalDate.java:400)
at java.time.LocalDate.parse(LocalDate.java:385)
at InventorySort.main(InventorySort.java:141)
2
  • 1
    "Not working" - how? You should give short snippets of the code you tried, and tell us what exactly didn't work in them. The whole program is really irrelevant. You just need to give us the minimal code that shows your problem. Two notes: (1) it's better to keep the data as Dates from the start rather than convert it when you search for it. Input the data and convert before storing in the list. (2) Consider using Java 8's LocalDate instead of the venerable and problematic Date. Commented Jul 30, 2015 at 18:59
  • Thanks for letting me know. I added the code that didn't work and added the error message I'm getting as well. I also changed the code to use LocalDate instead of Date. Commented Jul 30, 2015 at 20:58

2 Answers 2

1

From your example:

// Gets today's date

    Date todayDate = Calendar.getInstance().getTime();
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.UK);

You have return date in string format as below:

videos.add(new InventoryRow("Jurassic Park", "Regular", 'N', "30/07/2015"));

Now the difference between current day and return date:

        Date todayDate = Calendar.getInstance().getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.UK);
        String currDateStr = dateFormat.format(todayDate);
        String returnDateStr = "01/08/2015";
        Date returnDate = null;
        try {
            returnDate = dateFormat.parse(returnDateStr);
            todayDate = dateFormat.parse(currDateStr);
        }
        catch (ParseException e) {
            e.printStackTrace();
        }
        long diffInDays = (todayDate.getTime() - returnDate.getTime()) / (24 * 60 * 60 * 1000);
        if (diffInDays == 0) {
            System.out.println("Video is due today!");
        }
        else if (diffInDays > 0) {
            System.out.println("Video is overdue :(");
        }
        else {
            System.out.println("Video returned in advance :) ");
        }
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you but the problem is that the inputted string at the top of the code will be changing depending on the user's input so I need to get the return date from the specified InventoryRow in the ArrayList. Would this work for that?
yes. If the return date string from InventoryRow has the format dd/MM/yyyy .
But how do I change your code so that the return date string isn't set but can change depending on which video the user inputs in line4? Each video will have a different return date so 30/07/2015 only applies to Jurassic Park. I know right now I only have one return date in my Array List but in the future I will have more.
Okay I think I worked it out but for some reason when I set the return date of Jurassic Park to 01/08/2015, it returns "Video is due today!" even though that's tomorrow? However, if I set the return date to any other date in the future (02/08/2015 and beyond), it works just fine. I also get the right result if I set it to today, yesterday etc. It just seems to be tomorrow that's the problem. Do you know why this could be?
The problem is we didn't truncate the time in the todayDate which holds the current date value. Now edited the answer with corrections.
|
0

One thing you can do is instead of trying to covert "dates" is to convert the strings that represent the dates to numbers. The way you do this is by parsing a String to an Integer in this case. For example:

class Example {
    public static void main(String[] args) {
        String Date = "07/30/2015";
        String[] DatesTxt = Date.split("/");
        int[] DatesInt = new int[3];
        for (int i = 0; i < DatesTxt.length; i++) {
            DatesInt[i] = Integer.parseInt(DatesTxt[i]);
        }
        if (DatesInt[1] < 31) {
            System.out.println("And look am comparing dates!");
        }
    }
}

I hope this helped :).

1 Comment

Thank you but I'm really keen on converting into dates and using them to compare unless this is absolutely the only way to do it. But I'll definitely keep this in mind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.