2

每个人!我正在想办法从使用 LocalDate 的用户那里获取日期输入。我收到一条错误消息,提示“类型不匹配:无法从 String 转换为 LocalDate。” 我知道为什么会发生此错误,但我想知道是否有其他方法可以解决此问题。

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

我对Java真的很陌生,所以任何帮助都将不胜感激!谢谢!

4

1 回答 1

2

将您的回报更改dateInputLocalDate

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

并修改:

LocalDate newDate = dateInput(stringInput("Enter a date (like 3/3/17): "));

除此之外,您还需要关心yyyy格式化程序

于 2017-03-01T03:49:09.917 回答