-1

新しい Dillo を返し、新しい Dillo の長さを出力するようにします。コードをコンパイルすると、次のように表示されます: Error: Unreachable code for the lineSystem.out.println(this.length);どうすれば修正できますか? ありがとうございました

import tester.* ;

class Dillo {
    int length ;
    Boolean isDead ;

    Dillo (int length, Boolean isDead) {
      this.length = length ;
      this.isDead = isDead ;
    }

    // produces a dead Dillo one unit longer than this one
    Dillo hitWithTruck () {
      return new Dillo(this.length + 1 , true) ;
      System.out.println(this.length);
    } 
}

  class Examples {
    Examples () {} ;
    Dillo deadDillo = new Dillo (2, true) ;
    Dillo bigDillo = new Dillo (6, false) ;
 }
4

4 に答える 4

3

System.out返却後お持ちいただきます

Dillo hitWithTruck () {
    System.out.println(this.length);
    return new Dillo(this.length + 1 , true) ;
}
于 2015-05-12T20:15:55.633 に答える
1

print ステートメントの前に値を返すため、長さを出力する前に常にメソッドを終了します。コンパイラはこれを実行できないため、到達不能コードと見なします。コードを次から変更します。

    // produces a dead Dillo one unit longer than this one
Dillo hitWithTruck () {
  return new Dillo(this.length + 1 , true) ;
  System.out.println(this.length);
}

に:

    // produces a dead Dillo one unit longer than this one
Dillo hitWithTruck () {
  System.out.println(this.length);
  return new Dillo(this.length + 1 , true) ;
}
于 2015-05-12T20:22:42.660 に答える
1

ガストンの答えに基づいて構築するには:

Dillo hitWithTruck () {
    Dillo d = new Dillo(this.length + 1 , true);
    System.out.println(d.length);
    return d;
}

戻った後に長さを出力していたので、値を取得していませんでした。返される Dillo の長さを印刷したい場合は、上記のスニペットを試してください。

于 2015-05-12T20:23:33.110 に答える