我正在学习赫尔辛基大学的 Java 类(class),但我在示例 75.1 上遇到困难。
问题是我的方法不影响对象的值。例如,练习需要输出
value: 10
value: 9
value 8
但是,我收到:
value: 10
9
value: 10
9
value: 10.
我使用的代码是:
public void decrease() {
System.out.println(this.value - 1);
此外,我不能使用 return 语句,因为该方法必须为 void。
最佳答案
对。一般来说,“print x - 1”不会改变x的值。因此,我们必须更改 this.value
。我们通过分配来做到这一点:
public void decrease() {
this.value = this.value - 1; // decrease the value
System.out.println(this.value); // print the new value
}
我们实际上可以使用一元 --
运算符使用一行来完成此操作:
public void decrease() {
System.out.println(--this.value); // Decrease this.value first,
// then print the new value
}
注意 --
的位置。如果我们写--this.value
,我们会减少并然后打印。如果我们写 this.value--
,我们会打印然后减少。
关于java - 类值不受方法影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32131895/