我正在做Murach的Java编程教科书练习11-4,我已经掌握了前两种方法可以正常工作;但是我的shuffle方法根本不起作用。什么都没发生。
public static String[] suits = {"C", "S", "H", "D"};
public static int[][] cards = new int[4][13];
public static int used[] = new int[13];
public static void loadCards() {
for(int i = 0; i < cards.length; i++) {
for(int j = 0; j < cards[i].length; j++){
cards[i][j] = j+1;
}
}
}
public static void writeCards() {
for(int i = 0; i < cards.length; i++) {
System.out.print(suits[i] +" ");
for (int j = 0; j < cards[i].length; j++) {
System.out.print(cards[i][j]+ " ");
}
System.out.println("");
}
}
public static void shuffle() {
for (int i = 0; i < cards.length; i++) {
shuffle:
for (int j = 0; j < cards[i].length; j++) {
double d = Math.random() * 13;
int random = (int) d;
for(int test = 0; test<used.length;test++){
if(random == used[test]) {
break shuffle;
}
}
cards[i][j] = random;
}
}
}
public static void main(String[] args) {
loadCards();
writeCards();
System.out.println("");
shuffle();
writeCards();
}我觉得我开始用shuffle()方法把自己埋进一个错误的洞里。有没有什么简单的解决方法是我看不到的/我是不是在尝试完全错误的东西?
发布于 2016-07-21 04:15:31
我不能为你写随机代码,但是你可以使用像bogo sort这样的东西来随心所欲地随机编程。该算法既可用于打乱或混洗,也可用于教育目的,以说明为什么排序算法的效率如此重要。
发布于 2016-07-21 04:40:17
解决了这个问题,感谢Fred Larson为我指明了正确的方向。
public static void shuffle() {
for (int i = 0; i < cards.length; i++) {
for (int j = cards[i].length - 1; j > 0; j--) {
double d = Math.random() * 13;
int random = (int) d;
int a = cards[i][random];
cards[i][random] = cards[i][j];
cards[i][j] = a;
}
}
}https://stackoverflow.com/questions/38489978
复制相似问题