我想知道为什么生成的第一个数字总是" 0"。
以下是代码:
public static void main(String[] args) {
boolean[] pack = new boolean[52];
int[] cards = new int[5];
for (int i = 0; i < pack.length - 1; i++) {
System.out.print(pack[i] + " | ");
}
System.out.println();
Random give = new Random();
for (int i = 0; i < cards.length; i++) {
while (pack[cards[i]])
cards[i] = give.nextInt(5);
pack[cards[i]] = true;
System.out.println(cards[i]);
}
for (int i = 0; i < pack.length - 1; i++) {
System.out.print(pack[i] + " | ");
}
}
答案 0 :(得分:1)
因为pack(cards[i])
在第一次迭代时始终为false。解决方案可能是do-while
而不是while
。
检查一下:
import java.util.Random;
public class hw {
public static void main(String[] args) {
boolean[] pack = new boolean[52];
int[] cards = new int[5];
for (int i = 0; i < pack.length - 1; i++)
{
System.out.print(pack[i] + " | ");
}
System.out.println();
Random give = new Random();
for (int i = 0; i < cards.length; i++) {
do
{
cards[i] = give.nextInt(5);
}
while ( pack[cards[i]] );
pack[cards[i]] = true;
System.out.println(cards[i]);
}
for (int i = 0; i < pack.length - 1; i++)
{
System.out.print(pack[i] + " | ");
}
}
}
false |假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|
4
3
0
1
2
是的是的|是的|是的|是的|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|假|