我有课甲板
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());
}
}
}
实现接口
public interface DeckActions {
public Card draw();
public void shift(int times);
public void show();
}
我遇到的问题是Shift方法实际上并没有改变甲板阵列。 我错过了什么?我真的无法弄清楚。
这是我的主类,我试图用类似100或52的int调用该方法,但show总是显示相同的数组
public class TestCard {
public static void main (String [] args) {
Deck deck=new Deck();
deck.show();
deck.shift(52);
System.out.println("Shifted");
deck.show();
}
}
答案 0 :(得分:1)
问题是生成随机卡片交换的线路是外部循环,所以你总是交换相同的2张卡片。 尝试:
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:现场卡是静止的任何理由?