2017-03-01 71 views
2

大家好!我正試圖想辦法從用戶使用LocalDate獲取日期輸入。我收到一個錯誤,指出「類型不匹配:無法從字符串轉換爲LocalDate」。我知道爲什麼會發生這種錯誤,但我想知道是否有另一種方法來解決這個問題。輸入使用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的新手,所以任何幫助將不勝感激!謝謝!

+0

只要改變返回類型爲'LocalDate'和'返回日期;'。 – shmosel

+0

你的意思是改變我的dateInput參數從String到LocalDate?謝謝你的快速反應! – user7382031

回答

2

您的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格式化

+0

工作正常!非常感謝! – user7382031