2017-04-15 2 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. 
      } 

날짜 클래스의 가져 오기 및 설정 방법과 관련이 있지만 올바르게 수행하는 방법을 잘 모르겠습니다.

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()

말할 필요하다
관련 문제