2017-03-01 36 views
2

みんな!私は、LocalDateを使ってユーザーから日付入力を得る方法を考えようとしています。私は "タイプの不一致:Stringから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

ケア必要戻り日付; '。 – 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`と`に戻り値の型を変更するには、その横に

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

を使用すると、およそyyyyフォーマッタ

+0

それはうまくいった!どうもありがとうございます! – user7382031

関連する問題