Reputation: 13
i have class Deck
import java.util.Random;
public class Deck implements DeckActions{
private static Card[] cards=new Card[52];
public Deck () {
int i=0;
for (Suit suit : Suit.values()){
for (Rank rank : Rank.values()){
cards[i++]=new Card(rank,suit);
}
}
}
public Card draw() {
return cards[0];
}
public void shift(int times) {
Random randomGenerator=new Random();
int card1=randomGenerator.nextInt(52);
int card2=randomGenerator.nextInt(52);
for (int counter=0;counter < times; counter++){
Card temp=new Card(null,null);
temp=cards[card1];
cards[card1]=cards[card2];
cards[card2]=temp;
}
}
public void show() {
for (int i=0;i<cards.length;i++){
System.out.println(cards[i].toString());
}
}
}
that implements interface
public interface DeckActions {
public Card draw();
public void shift(int times);
public void show();
}
the problem i have is that the Shift method doesn't actually change the deck array. What am i missing? I really can't figure out.
This is my main class, i tried to call the method with an int like 100, or 52, but show always shows the same array
public class TestCard {
public static void main (String [] args) {
Deck deck=new Deck();
deck.show();
deck.shift(52);
System.out.println("Shifted");
deck.show();
}
}
Upvotes: 0
Views: 75
Reputation:
The problem is that lines which generate random indexes of cards to swap are outside loop, so all the time you swap the same 2 cards. Try:
public void shift(int times) {
Random randomGenerator=new Random();
for (int counter=0;counter < times; counter++){
int card1=randomGenerator.nextInt(52);
int card2=randomGenerator.nextInt(52);
Card temp=new Card(null,null);
temp=cards[card1];
cards[card1]=cards[card2];
cards[card2]=temp;
}
}
P.S: any reason for field cards to be static?
Upvotes: 1