它应该返回一组 6 个不同的整数。预先感谢您的帮助
附:我是这里的新手,所以,如果我以错误的方式提出问题,我深表歉意。
代码:
package net.javavideotutorials.assignment1;
import java.util.Set;
import java.util.Random;
public class LotteryNumberGenerator {
public static void main( String args[] ) {
Random rand = new Random();
int upperbound = 100;
int int_random = rand.nextInt(upperbound);
Set<Integer> a = new HashSet<Integer>();
if (a.size() <= 6) {
a.add(int_random);
} else {
System.out.println(a);
}
最佳答案
您正在使用if
条件并期望循环操作。
if
条件只检查一次,根据语句真或假运算提供输出。
if (a.size() <= 6) {
a.add(int_random);
} else {
System.out.println(a);
}
您可以稍微更改逻辑以满足您的需要。
while (a.size() <= 6) {
a.add(int_random);
}
System.out.println(a);
现在循环已经形成,但你又错过了一些东西。随机数生成应该在循环内部,否则每次都会是相同的随机数变量,并且 HashSet 会一次又一次地替换相同的值,然后您将得到无限循环。
所以你需要像这样在 while 循环中添加随机数生成。
while (a.size() <= 6) {
int_random = rand.nextInt(upperbound);
a.add(int_random);
}
System.out.println(a);
现在您不需要定义上面的随机数变量,因为您始终在添加 HashSet 之前在循环内生成。
这是完整的代码。
public class LotteryNumberGenerator {
public static void main(String args[]) {
Random rand = new Random();
int upperbound = 100;
Set<Integer> a = new HashSet<Integer>();
while (a.size() <= 6) {
int int_random = rand.nextInt(upperbound);
a.add(int_random);
}
System.out.println(a);
}
}
如果你只想设置6个数字,请修改while条件,如下所示。 <=
应修改为<
while (a.size() < 6) {
关于java - 这段代码无法编译,问题是什么(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62061554/