如何在Java中打印返回值字段

如何在Java中打印返回值字段,java,drjava,Java,Drjava,我希望它返回新的Dillo并打印出新Dillo的长度。当我编译代码时,它会说:Error:unreable code for the lineSystem.out.println(this.length)如何修复此问题?多谢各位 import tester.* ; class Dillo { int length ; Boolean isDead ; Dillo (int length, Boolean isDead) { this.length = le

我希望它返回新的Dillo并打印出新Dillo的长度。当我编译代码时,它会说:Error:unreable code for the line
System.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) ;
 }

返回后,您有
系统输出

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

在打印语句之前返回值,因此在打印长度之前始终退出该方法。编译器将其视为无法访问的代码,因为它永远不会执行。将代码更改为:

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


根据加斯顿的回答:

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

您在返回后打印出了长度,因此无法获得值。如果你想打印出你要返回的Dillo的长度,你应该试试上面我的snippit。

你的print语句永远不会执行,因为它前面有一个return语句

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

    } 
return语句用于从方法显式返回。也就是说,它使程序控制转移回方法的调用方。因此,它被归类为跳转语句。return语句执行后没有任何内容

更多信息

您的代码没有问题,这只取决于您希望它做什么。。。那么,你的问题是什么?我希望它返回新的Dillo并打印出新Dillo的长度。当我编译代码时,它会说:Error:unreable code for the line
System.out.println(this.length)谢谢。但我想打印出迪洛返回的长度。谢谢。但这会给我一个错误:错误:类型不匹配:无法从int转换为DilloThank you。现在可以了。但是我有一个新问题,为什么我把
返回d
系统输出打印项前(d.长度),则会出现以下错误:错误:无法访问的代码?
// produces a dead Dillo one unit longer than this one
    Dillo hitWithTruck () {
      System.out.println(this.length+1);
      return new Dillo(this.length + 1 , true) ;

    }