大家好,小弟刚开始自学java卡这个问题好几天了...
这段是参考"java se7 技术手册"后面的习题答案,
看了很久一直不懂在产生"乱数"(8~16行)后之后x[i]的值会刚好是1~52的数序,
而不会因为新的乱数造成重复值的发生呢??麻烦大家可以为小弟解惑,谢谢^^
public class s0402 {
public static void main(String[] args ) {
final int N = 52;
int[] x = new int[N + 1];
for(int i =1; i <= N; i++) {
x[i] = i;
}
for(int i = 1; i <= N; i++) {
int j = (int) (Math.random()*N);
if(j == 0){
j = 1;
}
int tmp = x[i];
x[i] = x[j];
x[j] = tmp;
}
for(int i = 1; i <= N; i++) {
switch((x[i] - 1) / 13) {
case 0: System.out.print("梅"); break;
case 1: System.out.print("桃"); break;
case 2: System.out.print("砖"); break;
case 3: System.out.print("心");
}
int remin = x[i] % 13;
switch(remin) {
case 0: System.out.print(" K "); break;
case 12: System.out.print(" Q "); break;
case 11: System.out.print(" J "); break;
default: System.out.printf("%2d ",remin);
}
System.out.printf("%c",i % 13 == 0 ? '\n' : ' ' );
}
}
}