2017-04-15 59 views
0

我想打印日期(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(); 
} 

回答

1

我想打印的日期(myDates)陣列中的每一日期對象到 屏幕。

首先,對於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()