[英]How to get ArrayList shuffle to produce more than one not all the same
Hi complete novice with Java, this is my second assignment. 嗨,用Java完成新手,这是我的第二个任务。 I have written a method for a lottery code using array list, I have two issues: 我用阵列列表编写了一个彩票代码的方法,我有两个问题:
public static void irishLottery() {
Scanner input = new Scanner(System.in);
double cost = 0;
System.out.println("How many lines of lottery up to 10 would you like?");
int linesam = input.nextInt();
ArrayList<Integer> numbers = new ArrayList<Integer>();
//define ArrayList to hold Integer objects
for (int lottonos = 0; lottonos < 45; lottonos++) {
numbers.add(lottonos + 1);
}
Collections.shuffle(numbers);
System.out.print("Your lottery numbers are: ");
for (int lncounter = 1; lncounter <= linesam; lncounter++) {
for (int j = 0; j < 6; j++) {
System.out.println(numbers.get(j) + " ");
}
}
}
For the first problem: reshuffle the list each time you want to display a new line: 对于第一个问题:每次要显示新行时重新洗牌:
for (int lncounter = 1; lncounter <= linesam; lncounter++) {
Collections.shuffle(numbers);
for (int j = 0; j < 6; j++) {
System.out.println( numbers.get(j) + " ");
}
}
For the second problem, don't use println(), but print(), since println() prints a new line: 对于第二个问题,不要使用println(),而是print(),因为println()会打印一个新行:
for (int lncounter = 1; lncounter <= linesam; lncounter++) {
Collections.shuffle(numbers);
for (int j = 0; j < 6; j++) {
System.out.print(numbers.get(j) + " ");
}
System.out.println(); // new line before next line
}
Note that the standard idiom for looping in Java consists in starting from 0: 请注意,Java中循环的标准习惯用法是从0开始:
for (int lncounter = 0; lncounter < linesam; lncounter++) {
Collections.shuffle(numbers);
for (int j = 0; j < 6; j++) {
System.out.print(numbers.get(j) + " ");
}
System.out.println(); // new line before next line
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.