0

这是我的一些代码:

           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,但没有任何效果。提前致谢。

4

1 回答 1

0

在 class 的所有if子句中,您都在为andPlayerInfo赋值。例如:XY

 this.X = 0;
 this.Y = 0;

这就是值发生变化的原因,因为XY变量是static。删除static两个变量的PlayerInfo,然后您将获得所需的行为。

static变量在类的不同对象之间共享。因此,如果您分配了P1.X = 10,那么P2.X, P3.X,P4.X等也将成为10所有对象共享的同一个变量。

于 2013-06-13T23:01:00.283 回答