以下是我的一些代码:
PlayerInfo P1 = new PlayerInfo();
P1.setInfo(1);
System.out.println("" + P1.X + "," + P1.Y);
PlayerInfo P2 = new PlayerInfo();
P2.setInfo(2);
System.out.println("" + P1.X + "," + P1.Y);
PlayerInfo P3 = new PlayerInfo();
P3.setInfo(3);
System.out.println("" + P1.X + "," + P1.Y);
PlayerInfo P4 = new PlayerInfo();
P4.setInfo(4);
System.out.println("" + P1.X + "," + P1.Y);
玩家信息定义为:
public class PlayerInfo{
public static int Range;
public static int X;
public static int Y;
public static int Score;
public static int Lives;
private static ImageIcon image;
public PlayerInfo(int Num){
Range = 1;
if(Num == 1){
this.X = 0;
this.Y = 0;
//System.out.println("" + X + "," + Y);
image = new ImageIcon("H:\\My Pictures\\BomberMan\\BMBlack.png");
}
else if(Num == 2){
this.X = 16;
this.Y = 0;
//System.out.println("" + X + "," + Y);
image = new ImageIcon("H:\\My Pictures\\BomberMan\\BMWhite.png");
}
else if(Num == 3){
this.X = 0;
this.Y = 16;
//System.out.println("" + X + "," + Y);
image = new ImageIcon("H:\\My Pictures\\BomberMan\\BMRed.png");
}
else if(Num == 4){
this.X = 16;
this.Y = 16;
//System.out.println("" + X + "," + Y);
image = new ImageIcon("H:\\My Pictures\\BomberMan\\BMBlue.png");
}
Score = 0;
Lives = 3;
}
现在我的代码正在显示:
0,0
16,0
0.16
16,16-
何时显示:
0,0
0,0
0,0
0,0
因为P1.X和P1.Y初始化为0和0而不应该在我的代码中更改。 我不知道为什么它在改变P1.X和P1.Y值的时候我根本不碰它们。有人可以向我解释一下吗?注意:我已经尝试创建一个单独的方法来设置信息和一个PlayerInfo数组,但没有任何作用。提前谢谢。
答案 0 :(得分:0)
在if
课程的所有PlayerInfo
子句中,您要为X
和Y
分配值。例如:
this.X = 0;
this.Y = 0;
由于X
和Y
变量为static
,因此值正在发生变化。
删除static
中两个变量的PlayerInfo
,然后您将获得所需的行为。
static
变量在类的不同对象之间共享。因此,如果您分配了P1.X = 10
,那么P2.X
,P3.X
,P4.X
等也将成为10
,因为所有对象都共享同一个变量。< / p>