-1

我希望它返回新的 Dillo 并打印出新 Dillo 的长度。当我编译代码时,它会说:错误:该行的代码无法访问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) ;
 }
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 回答
0

您的 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 语句执行后什么都没有。

更多信息

https://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html

于 2015-05-12T20:33:33.427 回答