如何在对象中存储值?

时间:2020-10-23 13:47:29

标签: java

每次尝试使用roll方法时,我都试图为每个骰子对象设置两个不同的faceValue:dice1和dice2。但是,每次我使用dice1.roll()时,都会像这样对faceValue进行更新。或dice2.roll();。

如何获取每次滚动时每个对象的更新,所以dice1.faceValue不等于dice2.faceValue?

public class Dice {

    private final static int diceFaces = 6;
    private static int faceValue;

    // test method
    public static void main(String[] args)
    {
        Dice dice1 = new Dice("dice1");
        Dice dice2 = new Dice("dice2");
        int i;
        for(i = 0; i < 20; i++)
        {
            dice1.roll();
            System.out.println("test Dice One "+dice1.faceValue);
            dice2.roll();
            System.out.println("test Dice Again "+dice1.faceValue);
        }
    }


    public Dice(String nameInput)
    // sets a constructor for the object Dice.
    {
        String diceName;
        int faceValue;
    }

    public int roll()
    // method that generates a random value for faceValue contingent on diceFaces and numberofDices.
    {
        faceValue = (int) (Math.random() * diceFaces) + 1;
        return faceValue;
    }


0 个答案:

没有答案