Tho*_*eia 0 java variables global-variables
我有这个代码:
public void onPlayerInteract(PlayerInteractEvent event) {
final Action action = event.getAction();
Location l1 = null;
Location l2 = null;
if (action == Action.LEFT_CLICK_BLOCK){
l1 = event.getClickedBlock().getLocation();
} else if (action == Action.RIGHT_CLICK_BLOCK) {
l2 = event.getClickedBlock().getLocation();
}
Thread t = new Thread() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000*60*60);
Location maxx = l1.getX();
Location maxy = l1.getY();
Location maxz = l1.getZ();
Location minx = l2.getX();
Location miny = l2.getY();
Location minz = l2.getZ();
if(l1.getX() > l2.getX()){
//I can't execute this, errors!
}
} catch (InterruptedException ie) {
}
}
}
};
t.start();
Run Code Online (Sandbox Code Playgroud)
它给了我错误,并说要将l1和l2改为决赛.如果我将l1和l2更改为决赛,它会给我另一个错误,即l1 =等等,它表示要删除最后一个.
l1并且l2是方法的局部变量onPlayerInteract().在此方法中,您将创建一个使用这些局部变量l1和的匿名内部类l2.这是如果只可能l1和l2是最终的决定.但是根据定义,最终变量只能分配一次,然后分配null,然后为它们分配另一个值.因此,您需要复制l1和复制l2最终变量,并在匿名类中使用这些最终副本:
public void onPlayerInteract(PlayerInteractEvent event) {
final Action action = event.getAction();
Location l1 = null;
Location l2 = null;
if (action == Action.LEFT_CLICK_BLOCK){
l1 = event.getClickedBlock().getLocation();
} else if (action == Action.RIGHT_CLICK_BLOCK) {
l2 = event.getClickedBlock().getLocation();
}
final Location l1Final = l1;
final Location l2Final = l2;
Thread t = new Thread() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000*60*60);
Location maxx = l1Final.getX();
Location maxy = l1Final.getY();
Location maxz = l1Final.getZ();
Location minx = l2Final.getX();
Location miny = l2Final.getY();
Location minz = l2Final.getZ();
if(l1Final.getX() > l2Final.getX()){
// ...
}
} catch (InterruptedException ie) {
}
}
}
};
...
}
Run Code Online (Sandbox Code Playgroud)