简体   繁体   中英

How to assign objects to an array?

So my array currently assign 5 instances of a dice object. My issue is that I have another class that needs to lock a dice from use.

   public class Yahtzee {
        OneDice[] dice = new OneDice[5];

        public Yahtzee() {
            yahtzeeRoll(); //constructor
        }

        public void yahtzeeRoll() {
            for (int i = 0; i != dice.length; i++) {
                dice[i] = new OneDice();
            }
  public void lock(int which) {

        dice[which - 1].lockDice();
        }
  }

however my dice[i] = new OneDice(); creates a whole new set of random numbers each time yahtzeeRoll is called.

here is the method passing the which parameter.

   @Override
    public void choose() {
        int which;
        Scanner sc = new Scanner(System.in);
        System.out.println(getName() + " Rolling.");
        hand.printYahtzee();

        System.out.println("Would you like to lock dice 1? 1 for yes");
        choice = sc.nextInt();
        if (choice == 1) {
            which = 1;
            hand.lock(which);
        }

how can I assign a random value to each dice index without creating a brand new set of rolls that negates the lock. At least that appears to be the issue to me?

It sounds like you need to just skip over entries which are locked:

for (int i = 0; i < dice.length; i++) {
    if (dice[i] == null || !dice[i].isLocked()) {
        dice[i] = new OneDice();
    }
}

Either that, or change your code to initialize dice in the constructor with new instances, but make your yahtzeeRoll method just change the values within the existing unlocked instances, instead of creating new instances. For example:

public Yahtzee() {
    for (int i = 0; i  < dice.length; i++) {
        dice[i] = new OneDice();
    }
    rollUnlocked();
}

public void rollUnlocked() { // Renamed from yahtzeeRoll for clarity
    for (OneDice die : dice) {
        die.rollIfUnlocked(); // Or whatever method you want
    }
}

(where rollIfUnlocked would reroll the single die, only if it hadn't previously been locked).

Don't reinitialize the entire array each time you roll. In real life when playing yahtzee you don't go grab 5 new dice every time you roll.

create OneDice as follows:

class OneDice {
   int value;
   boolean locked;

   void roll(){
      if(!locked)
         value = Math.nextInt(6);
   }

   int getValue(){
      return value;
   }
   void setLock(boolean lock){
      locked = lock;
   }
   boolean isLocked(){
      return locked;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM