vendredi 23 avril 2021

The && operator is not working correctly in this java program [duplicate]

For the past couple of days I have been struggling with this. I'm trying to generate an array of random playing cards, without any duplicates. This is an excerpt from the program:

public CardSet(int howMany)
   {
      startCount = howMany;
      set = new PlayingCard[startCount];
      for(int i = 0; i<startCount; i++)
      
      {
           
      boolean exist = true;
      while(exist){
      exist = false;
      int val = rand.nextInt(13)+1;
      int st = rand.nextInt(4)+1;
      PlayingCard x = new PlayingCard(
                (st==1)?"Clubs":
                (st==2)?"Diamonds":
                (st==3)?"Hearts":
                "Spades", val);

    
    for(int k = 0; k < i; k++){
     if(x.getSuit() == set[k].getSuit() && x.getValue() == set[k].getValue()){
      exist = true;
       break;}
    }
    if(!exist){
     set[i] = x;}
  }
    
                         
}
}

This is a method I've found works when I set the condition statement to if(x.getSuit() == set[k].getSuit()), if(x.getValue() == set[k].getValue()), and if((x.getSuit() == set[k].getSuit()) || (x.getValue() == set[k].getValue())), but for some reason, the condition statement I used in the above block of code is just not working. There are several duplicates. It only sometimes deletes them. I don't understand why this isn't working, it seems to me that it should by all accounts. I'm quite new to Java, so if there's something I'm missing I'd like to know. Just for context, getValue() and getSuit() are the getter methods for the value and suit of the playing cards respectively.

Aucun commentaire:

Enregistrer un commentaire