我想将日期数组 (myDates) 中的每个日期对象打印到屏幕上。 日期类具有月、日和年的值。
private static void printDates(Date[] myDates) throws IOException {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
if(myDates.length == 0) {
System.out.println("There are no dates to print.\n");
}
else {
System.out.println("Print the dates to the screen or to a file?");
System.out.println(" 1. Print to screen.");
System.out.println(" 2. Print to a new file.");
System.out.print("Choice: ");
int option = input.nextInt();
System.out.println("");
if(option == 1) {
for(int i = 0; i < myDates.length; i++) { //Is this necessary?
//Don't know how to print array of objects with toString method in date class.
}
我认为这与日期类的 get 和 set 方法有关,但不太确定如何正确执行这些操作。
public String getDate() {
return "" + month.getMonth() + " " + day.getDay() + " " + year.getYear();
}
public void setDate(Date date) {
//maybe make a date string then this.date = date; ???
}
或者也许您会使用日期类的 toString 方法?这可能不正确。
public String toString(e) {
return getMonthWord(day.toString()) + " " + month.toString() + " " + year.getYear();
}
最佳答案
I want to print each date object in the array of dates (myDates) to the screen.
首先,对于 toString()
方法,您不需要传入参数,因为您已声明您创建的 toString()
方法确实是不正确。
更改此:
public String toString(e) {
return getMonthWord(day.toString()) + " " + month.toString() + " " + year.getYear();
}
对此:
public String toString() {
return this.day + " / " + this.month + " / " + this.year;
}
考虑到数组中的每个日期都有一个toString()
,您可以简单地执行以下操作:
if(option == 1) {
Arrays.stream(myDates).forEach(System.out::println);
}
或使用典型的 foreach 循环:
if(option == 1) {
for(Date d : myDates) System.out.println(d);
}
基本上,每当 System.out.println
调用数组中的任何 Date
对象时,都会发生 toString()
方法会针对特定的 Date
对象自动调用,您无需说 d.toString()
关于java - 如何将对象数组打印到屏幕上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43431753/