-4

これまでのところ、私のコードは次のようになります。

public class Tree {
  public static void main (String[] argv) {
    int serial; //create parameters
    double circumference;
    String species;      
  }
  public Tree(int serial, double circumference, String species) {
    String.format("Tree number %d has a circumference of %.2f and is of species %s.", 
        serial, circumference, species);
  }  
}

ツリー情報を非常に特殊な形式でdescribe()返すメソッドを作成する方法がわかりません。String

4

2 に答える 2

4

describe メソッド コードを Tree コンストラクタに入れようとしています。そうしないでください。コンストラクターを使用してフィールドを初期化し、書式設定された文字列を返す describe メソッドを作成します。

public class Tree {
  // private Tree fields go here

  public Tree(int serial, double circumference, String species) {
    // initialize the Tree fields here
  }

  public String describe() {
    // return your formatted String describing the current Tree object here
  }
}

余談ですが、あなたの main メソッドは実際には何も役に立たず、describe メソッドをテストできるようにする Tree のインスタンスを作成しません。

于 2013-09-04T04:23:14.200 に答える
1

メソッドString.formatStringすでに

public String describe(){
      return String.format("Tree number %d has a circumference of %.2f and is of species %s.", serial, circumference, species);
}

メソッドをオーバーライドtoString()して、オブジェクトに関する意味のある情報を提供することをお勧めします

public String toString(){
    return String.format("Tree number %d has a circumference of %.2f and is of species %s.", serial, circumference, species);
}
于 2013-09-04T04:19:41.360 に答える