我想通过扫描器实例化另一个类的对象,但我需要传递的参数之一是LocalDate 类型。这就是为什么我在我的主类中创建了一个方法,以便
- 按给定顺序向用户询问字符串输入(例如 dd. MMM. yyyy)
- 然后我的程序接受该输入并将其保存为字符串,以便稍后将其显示给用户
但我遇到了一个错误。下面是我的生日课和我主要课的相关部分。
生日.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;
}
}
主.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));
并将其存储在一个名为 addedDate 的字符串中?但对我来说,这似乎是一个非常错误的思考过程,所以最后我想知道我在 addDate() 方法中分别要求年/月/日的方法是什么让它出错了?