2014-02-27 3 views
0

배열은 String입니다. 모든 객체를 인쇄하려면 for 루프를 사용하고 싶습니다. 나는 루프를 만들고 나서 String을 반환함으로써 이것이 이루어질 것이라는 인상을 받고 있었다. 나는 이것을 성취하기 위해 내가 무엇을 바꿔야하는지 확신하지 못한다. 다음 내 노력 :for 루프를 사용하여 모든 배열을 Java로 인쇄하는 방법

public class SolarSystem { 
     private Planet[] planets; 
     private int position = 0; 
    public SolarSystem(int size) { 
     planets = new Planet[size]; 
    } 
    public void add(Planet planet) { 
     planets[position] = planet; 
     position++; 
    } 
    public String toString(){ 
      for(int i = 0; i < planets.length; i++){ 

      } 
      return toString(); 
    } 
    } 

ADDED PLANET CLASS

public class Planet { 


    String name; 
    int moons; 

    public Planet(String name, int moons) 
    { 
     this.moons = moons; 
     this.name = name;    
    } 

    public String toString() { 
     return "The Planet " + name + " Has " + moons + " Moon(s) \r\n "; 
    } 

} 
+0

'System.out.println (planets [i])'doesn 격차를 메우지 않습니까? – ItachiUchiha

답변

1

재정 toString() 방법 Planet 클래스 및 코드 아래 사용

public String toString(){ 
     String result = ""; 
     for(int i = 0; i < planets.length; i++){ 
      result += planets[i].toString(); // append comma if you need to separate it, 
          // and most of all handle nulls 
     } 
     return result; 
} 
+0

이것은 toString 메서드에 추가 되었기 때문에 결과를 얻기 위해 toString 메서드를 호출하는 것으로 간주됩니까? 나는 아마 그 바보 같은 질문을 알고 있지만 이것 주위에 내 머리를 감싸하려고 ... :/ – wuno

+0

정확 하 게. 모범 사례는 필요한 세부 사항을 사용자에게 달려 있지만 사용자 정의 할 수 있습니다. 'StringBuilder'의 사용은 좋은 연습입니다. 그래서 Christian +1을주었습니다. –

+0

은 Planet toString 메서드가 어떻게 보이는지 보여주기 위해 답을 편집 할 것을 제안합니다. –

2

당신은 StringBuilder 사용해 볼 수 있습니다 :

를 당신이 호출 클래스에서

public String toString(){ 
    StringBuilder result = new StringBuilder(); 

    String NEW_LINE = System.getProperty("line.separator"); 

    result.append(" planetProperty1: ").append (planetProperty1).append(NEW_LINE); 
    result.append(" planetProperty2: ").append (planetProperty2).append(NEW_LINE); 

    return result.toString(); 
} 

다음 행성 클래스에서이 오버라이드 (override) 방법이있는 경우

0

당신은

System.out.println (planets[i].toString()); 
+0

'+'로 연결하는 대신에 별도의'append()'를 사용하십시오. 그래서'StringBuilder'를 사용하고 있습니다. – Christian

+0

사실입니다. 감사합니다. –

1
public String toString() { 
StringBuilder mainresult = new StringBuilder(); 
for(int i = 0; i < planets.length; i++){ 
    StringBuilder result = new StringBuilder(); 
    String newLine = System.getProperty("line.separator"); 

    result.append(planets[i].getClass().getName()); 
    result.append(" Object {"); 
    result.append(newLine); 

    //determine fields declared in this class only (no fields of superclass) 
    Field[] fields = this.getClass().getDeclaredFields(); 

    //print field names paired with their values 
    for (Field field : fields ) { 
    result.append(" "); 
    try { 
     result.append(field.getName()); 
     result.append(": "); 
     //requires access to private field: 
     result.append(field.get(this)); 
    } catch (IllegalAccessException ex) { 
     System.out.println(ex); 
    } 
    result.append(newLine); 
    } 
    result.append("}"); 
    //if it is the first one then no new line added 
    if(i==0) 
    { 
    mainresult.append(result.toString()); 
    continue; 
    } 
    mainresult.append(newLine); 
    mainresult.append(result.toString()); 
} 
    return mainresult.toString(); 
} 
0

toString를 오버라이드 (override)() 메소드

호출 컬렉션을 반복 할 수 있습니다
@Override 
public String toString() { 
    return "SolarSystem [te=" + Arrays.toString(te) + ", position=" + position + "]"; 
} 
관련 문제