0

スキャナーを介して別のクラスのオブジェクトをインスタンス化したいのですが、渡す必要があるパラメーターの 1 つはLocalDate 型です。これが、メインクラスにメソッドを作成して、

  • 指定された順序で文字列入力をユーザーに要求します (例: dd. MMM. yyyy)
  • 次に、私のプログラムはその入力を受け取り、それを文字列として保存して、後でユーザーに表示します

しかし、私はエラーで立ち往生しています。以下は私の誕生日クラスとメインクラスの関連部分です。

Birthday.java :

public class Birthday {
    String name;
    LocalDate date;
    int age;
    boolean gift;

    public Birthday(String name, LocalDate date, int age, boolean gift) {
        this.name = name;
        this.date = date;
        this.age = age;
        this.gift = gift;
    }
}

Main.java :

public static void addBirthday(){
        Scanner scan = new Scanner(System.in);
        //below I want to instantiate a Birthday obj
        Birthday bday = new Birthday(scan.nextLine(), addDate(), scan.nextInt(), scan.nextBoolean());
        
        bdays.add(bday); //this is referring to an ArrayList I didn't include in this excerpt   
        scan.close();
    }

...

 public static String addDate() {
        Scanner scan = new Scanner(System.in);
        LocalDate ld = LocalDate.of(scan.nextInt(), scan.nextInt(), scan.nextInt());
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd. MMM. yyyy");
        System.out.println(ld.format(dtf));
        scan.close();
        //return addedDate??;
    }

インスタンス化で発生し続けるエラーは、「互換性のない型: java.lang.String を java.time.LocalDate に変換できません」です。addDate() メソッドを無効にすると、メソッドを使用できないという別のエラーが発生します。

コメントアウトされた return ステートメントは、私が可能だと思ったものSystem.out.println(ld.format(dtf));です。しかし、私の側では非常に間違った思考プロセスのように思われるので、最終的には、年/月/日を個別に要求する addDate() メソッドでの私のアプローチが間違っているのでしょうか?

4

2 に答える 2