2017-04-15 4 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() { 
    return this.day + "/" + this.month + "/" + this.year; 
} 

toString()持って、あなたは、単にこれを行うことができます:これまで

public String toString(e) { 
    return getMonthWord(day.toString()) + " " + month.toString() + " " + year.getYear(); 
} 

if(option == 1) { 
    Arrays.stream(myDates).forEach(System.out::println); 
} 

または一般的な使用foreachループ:

その後 toString()メソッドは、その特定 Dateオブジェクトに対して自動的に呼び出され、アレイ内の任意の Dateのオブジェクトを呼び出すたび
if(option == 1) { 
    for(Date d : myDates) System.out.println(d); 
} 

基本的には、何が起こるかは、あなたがd.toString()

言う必要はありません、です
関連する問題