数组元素在添加其他元素时会相互覆盖

时间:2019-01-23 19:32:39

标签: java arrays duplicates

我想用Java创建宠物商店/商店游戏,在这个游戏中,您可以创建多只狗。当您输入“ doginfo”时,程序将显示您所有狗的信息。 (这就是“目标”)

我尝试制作一个包含1000个哺乳动物元素的数组,并在每次创建一条狗时添加与该狗的信息相对应的元素。

class PetShop的一部分:

public static int count = 0;

if(cmd.equalsIgnoreCase("dogInfo"))
{
    Mammal.dogInfo();
}

private static void createDog() 
{       

    System.out.print("Select the name of your dog: ");
    String name = scan.nextLine();
    System.out.print("Select the colour of your dog: ");
    String colour = scan.nextLine();
    System.out.print("Select the maximum height of your dog (cm): ");
    double maxHeight = scan.nextDouble();
    System.out.print("Select the gender of your dog (0 - female, 1 - male): ");
    int intGender = scan.nextInt();
    boolean male;

    if(intGender == 0)
    {
        male = false;
        err = false;
    }
    else if(intGender == 1)
    {
        male = true;
        err = false;
    }
    else
    {
        male = false;
        err = true;
    }

    if (err == false)
    {
        Mammal.mArray[count] = new Mammal(name, colour, maxHeight, male);
        count++;        
        System.out.println("A new dog was created!");
    }
    else
    {
        System.out.println("Select between 0 and 1!");
        return;
    }
}


class Mammal的一部分:

public static Mammal[] mArray = new Mammal[1000];

private static String name,colour;
private static double height,maxHeight;
private static int health;
private static boolean male;

//constructor
public Mammal(String n, String c, double mH, boolean m)
{
    name = n;
    colour = c;
    height = 9;
    maxHeight = mH;
    health = 100;
    male = m;
}

@Override
public String toString()
{
    return String.format("Name: %s, Colour: %s, Age: %d, Health: %d, Height: %.2f, Maximum Height: %.2f, Gender: %s"
                ,name, colour, age, health, height, maxHeight, male ? "Male" : "Female"
        );
}

public static void dogInfo()
{
    for (int i = 0; i < mArray.length; i++) {
        if (mArray[i] != null)
        {
            System.out.println(mArray[i]);
        }
    }
}

很抱歉,如果代码过多^-^。

如果我输入的第一个狗叫史蒂夫,颜色是棕色,maxHeight 60,男性1,第二个输入的狗叫丹妮尔,颜色是白色,maxHeight 45,男性0,那么当我输入“ doginfo”时,我会期望< / p>

Name: steve, Colour: brown, Age: 0, Health: 100, Height: 9,00, Maximum Height: 60,00, Gender: Male
Name: danielle, Colour: white, Age: 0, Health: 100, Height: 9,00, Maximum Height: 45,00, Gender: Female

但实际输出是

Name: danielle, Colour: white, Age: 0, Health: 100, Height: 9,00, Maximum Height: 45,00, Gender: Female
Name: danielle, Colour: white, Age: 0, Health: 100, Height: 9,00, Maximum Height: 45,00, Gender: Female

出什么问题了?

1 个答案:

答案 0 :(得分:0)

将变量声明为static时,对其进行更改将使其对于您的类的每个实例都更改。

为避免此行为,请不要将它们声明为静态,并且引用变量(声明位置除外)

this.variableName

代替

variableName

以便您的程序访问在其上调用了该函数的对象变量,而不是其他一些全局变量。