如何将Java中变量的当前值声明为final?
How to declare the current value of a variable in Java as final?
我目前正在 Java 中编写一个程序,其中移动对象需要在生成新对象时将其位置设置为其最终位置,以便它们不再受键盘命令的影响。我熟悉将实例变量声明为 final,但我正在寻找一种在实例化后锁定变量的方法。
即
boolean beentype = StdDraw.hasNextKeyTyped();
if (beentype) {
if (this.y > 1) {
char key = StdDraw.nextKeyTyped();
char a1 = 'a';
char d = 'd';
if (key == a1 && this.x > 2 && position [i-1][j] == 0) {
this.x = this.x - movePerCall;
j = j + 1;
position[i + 1][j - 1] = 0;
position[i][j - 1] = 0;
position[i][j] = 1;
}
if (key == d && this.x < 19 && position [i-1][j] == 0) {
this.x = this.x + movePerCall;
j = j - 1;
position[i + 1][j + 1] = 0;
position[i][j + 1] = 0;
position[i][j] = 1;
}
}
一旦变量满足其 isDone 布尔要求,我希望 this.x 和 this.y 不再更改
谢谢
虽然更改设计可能有意义,但我不知道您需要这个功能的问题是什么,因为您要求一个可锁定的整数 class:
public class LockableInt {
private int value;
private boolean locked = false;
public LockableInt(int initial) {
value = initial;
}
public void setLock(boolean locked) { this.locked = locked; }
/* Sets the value if not locked, otherwise does nothing.
*/
public void setValue(int value) {
if (!locked) {
this.value = value;
}
}
public int getValue() {
return value;
}
}
所以现在如果你使用这个 class 而不是普通的 int
:
而不是 this.x = this.x - movePerCall;
你会做 this.x.setValue(this.x.getValue() - movePerCall);
如果值应该被锁定你做 this.x.setLock(true)
之后每个后续调用 this.x.setValue(...)
将没有效果。
如果以后要锁定的不仅仅是整数类型的变量:
您当然可以轻松地生成我上面发布的 class 并将其重复用于您在应用程序中使用的任何类型。
我目前正在 Java 中编写一个程序,其中移动对象需要在生成新对象时将其位置设置为其最终位置,以便它们不再受键盘命令的影响。我熟悉将实例变量声明为 final,但我正在寻找一种在实例化后锁定变量的方法。
即
boolean beentype = StdDraw.hasNextKeyTyped();
if (beentype) {
if (this.y > 1) {
char key = StdDraw.nextKeyTyped();
char a1 = 'a';
char d = 'd';
if (key == a1 && this.x > 2 && position [i-1][j] == 0) {
this.x = this.x - movePerCall;
j = j + 1;
position[i + 1][j - 1] = 0;
position[i][j - 1] = 0;
position[i][j] = 1;
}
if (key == d && this.x < 19 && position [i-1][j] == 0) {
this.x = this.x + movePerCall;
j = j - 1;
position[i + 1][j + 1] = 0;
position[i][j + 1] = 0;
position[i][j] = 1;
}
}
一旦变量满足其 isDone 布尔要求,我希望 this.x 和 this.y 不再更改 谢谢
虽然更改设计可能有意义,但我不知道您需要这个功能的问题是什么,因为您要求一个可锁定的整数 class:
public class LockableInt {
private int value;
private boolean locked = false;
public LockableInt(int initial) {
value = initial;
}
public void setLock(boolean locked) { this.locked = locked; }
/* Sets the value if not locked, otherwise does nothing.
*/
public void setValue(int value) {
if (!locked) {
this.value = value;
}
}
public int getValue() {
return value;
}
}
所以现在如果你使用这个 class 而不是普通的 int
:
而不是 this.x = this.x - movePerCall;
你会做 this.x.setValue(this.x.getValue() - movePerCall);
如果值应该被锁定你做 this.x.setLock(true)
之后每个后续调用 this.x.setValue(...)
将没有效果。
如果以后要锁定的不仅仅是整数类型的变量:
您当然可以轻松地生成我上面发布的 class 并将其重复用于您在应用程序中使用的任何类型。