everyone! I am trying to think of a way to get a date input from user using LocalDate. I am getting an error that says "Type mismatch: cannot convert from String to LocalDate." I know why this error is happening but I want to know if there's another way to get around this.
String newName = stringInput("Enter a product name: ");
String newStore = stringInput("Enter a store name: ");
LocalDate newDate = dateInput("Enter a date (like 3/3/17): ");
double newCost = doubleInput("Enter cost: ");
/* the third parameter of Purchase2 is a LocalDate which I think is the reason for my error.
* Is there any way to get around this?
*/
Purchase2 purchase = new Purchase2(newName, newStore, newDate, newCost);
purchases.add(purchase); // I'm adding these to an ArrayList
/*
* This is the method I created for newDate
* I need to take the date as String and convert it to LocalDate
*/
public static String dateInput(String userInput) {
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("M/d/yyyy");
LocalDate date = LocalDate.parse(userInput, dateFormat);
System.out.println(date);
return userInput;
}
I am really new to Java so any help will be appreciated! Thank you!
Change your return of dateInput
to LocalDate
public static LocalDate dateInput(String userInput) {
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("M/d/yyyy");
LocalDate date = LocalDate.parse(userInput, dateFormat);
System.out.println(date);
return date ;
}
And modify :
LocalDate newDate = dateInput(stringInput("Enter a date (like 3/3/17): "));
Beside that you need care about yyyy
formatter