【问题标题】:taking input using LocalDate使用 LocalDate 获取输入
【发布时间】:2017-07-20 06:00:02
【问题描述】:

大家!我正在想办法从使用 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 新手,所以任何帮助都将不胜感激!谢谢!

【问题讨论】:

  • 只需将返回类型改为LocalDatereturn date;即可。
  • 您的意思是将我的 dateInput 参数从 String 更改为 LocalDate?感谢您的快速回复!

标签: java localdate dateformatter


【解决方案1】:

dateInput 的返回值更改为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 ;
}

并修改:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 2015-03-17
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多