Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何生成三个不相等的数字?_Java_Arrays_For Loop_Jvm_Set - Fatal编程技术网

Java 如何生成三个不相等的数字?

Java 如何生成三个不相等的数字?,java,arrays,for-loop,jvm,set,Java,Arrays,For Loop,Jvm,Set,这里是数字生成: for( int i=0; i<3; i++) { int randomNumbers = random.nextInt(10) + 1; } 在这里我可以收到相同的数字 例如:5,7,5 但我只需要收到不同的数字:5,1,9 是否可以使用一些小代码,或者我应该为其编写一些方法?您可以使用只包含唯一值的集合: Set<Integer> randomInts = new HashSet(); while(randomInts.size() <

这里是数字生成:

for( int i=0; i<3; i++) {
    int randomNumbers = random.nextInt(10) + 1; 
}
在这里我可以收到相同的数字

例如:5,7,5

但我只需要收到不同的数字:5,1,9

是否可以使用一些小代码,或者我应该为其编写一些方法?

您可以使用只包含唯一值的集合:

Set<Integer> randomInts = new HashSet();
while(randomInts.size() < 3) {
    randomInts.add(random.nextInt(10) + 1);
}
当然,您需要面对过采样,但如果性能不是最重要的,这种方法很容易扩展。

您可以使用只包含唯一值的集合:

Set<Integer> randomInts = new HashSet();
while(randomInts.size() < 3) {
    randomInts.add(random.nextInt(10) + 1);
}
当然,您需要面对过采样,但如果性能不是最重要的,这种方法很容易扩展。

这里有一种避免的方法:生成一个数字,最多10个,一个最多9个,最多8个。通过递增避免重复。这保证了均匀分布

int a=random.nextInt10+1; int b=random.nextInt9+1; 如果b>=a{b++;} int c=random.nextin8+1; ifc>=a>b?B:{C++,} ifc>=a>b?A: B{C++(}); 这里有一种避免的方法:生成一个数字,最多10个,一个最多9个,最多8个。通过递增避免重复。这保证了均匀分布

int a=random.nextInt10+1; int b=random.nextInt9+1; 如果b>=a{b++;} int c=random.nextin8+1; ifc>=a>b?B:{C++,} ifc>=a>b?A: B{C++(});
在我看来,使用while循环可以生成具有不同数字的随机数。使用while循环检查该数字是否在之前生成,然后再生成新数字。

在我看来,使用while循环可以生成具有不同数字的随机数字。使用while循环检查号码是否已提前生成,然后生成新号码。

改为执行while循环,检查是否已生成该号码。如果没有,则增加计数器,改为执行while循环,并检查是否已生成该数字。如果不是,则将计数器的长度缩短一点,不确定是好是坏:c>=a | c>=b和c>=a&c>=b。稍微缩短一点,不确定是好是坏:c>=a | c>=b和c>=a&c>=b。