嘿伙计们,我正在阅读Java编程入门书和其中一个练习:
经验洗牌检查。跑 计算实验检查 我们的洗牌代码就像 标榜。写一个程序 需要命令行的ShuffleTest 参数M和N,N个shuffles 一个初始化的大小为M的数组 在每次洗牌之前使用[i] = i,并且 打印M-by-M表,使得行i 给出了我结束的次数 在所有j的位置j。所有条目 在数组中应该接近N / M.
现在,这段代码只输出一个零块......
public class ShuffleTest2 {
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int [] deck = new int [M];
for (int i = 0; i < M; ++i)
deck [i] = i;
int [][] a = new int [M][M];
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
a[i][j] = 0 ;
for(int n = 0; n < N; n++) {
int r = i + (int)(Math.random() * (M-i));
int t = deck[r];
deck[r] = deck[i];
deck[i] = t;
for (int b = 0; b < N; b++)
{
for (int c = 0; c < M; c++)
System.out.print(" " + a[b][c]);
System.out.println();
}
}
}
}
}
}
我做错了什么? :(
由于
答案 0 :(得分:0)
所以a就像历史?就像你现在一样,它总是像你初始化一样填充零,你永远不会分配给它!在“shuffling”for循环之后,你需要设置
A[i][POSITION] = CARD_VALUE
意思是在第i次洗牌后,卡CARD_VALUE处于POSITION位置。我不想给你所有的细节,但是它将需要另一个for循环,并且用于打印的嵌套for循环需要独立于任何其他循环,在其他所有循环完成时发生。
看起来你有一些关于你需要仔细查看的for循环的事情。手动或使用调试器跟踪程序流程,您会注意到需要移动其中一些大括号和代码块。
- 尝试一下 -
public class ShuffleTest2 {
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
int [] deck = new int [M];
int [][] a = new int [M][M];
for (int i = 0; i < M; i++) { //initialize a to all zeroes
for (int j = 0; j < M; j++) {
a[i][j] = 0 ;
}
}
for(int i = 0; i < N; i++) //puts the deck in order, shuffles it, and records. N times
{
for (int j = 0; j < M; j++) //order the deck
deck[j] = j;
for(int j = 0; j < M; j++) { //shuffle the deck (same as yours except counter name)
int r = j + (int)(Math.random() * (M-j));
int t = deck[r];
deck[r] = deck[j];
deck[j] = t;
}
for(int j = 0; j < M; j++) //record status of this deck as described
{
int card_at_j = deck[j]; //value of card in position j
a[card_at_j][j]++; //tally that card_at_j occured in position j
}
} //big loop ended
for (int b = 0; b < M; b++) //print loop. a is MxM, so limit of N was wrong.
{
for (int c = 0; c < M; c++)
{
System.out.print(" " + a[b][c]);
System.out.println();
}
} //print loop ended
} //main() ended
} //class ended