尝试在Java中检查重复项 //此代码允许计算机从数组中选择第一个随机数 int rn1=boarduser[new Random().nextInt(boarduser.length)]; System.out.println(“计算机值:+rn1”); //此代码允许计算机从数组中选择第二个随机数 int rn2=boarduser[new Random().nextInt(boarduser.length)]; System.out.println(“计算机值:+rn2”); 布尔标记重复1;//检查计算机是否两次采用相同的值 对于(int j=0;j
首先,我想说我对Java的知识有限,所以这里就是 代码仍然不完整,但我要做的是检查在尝试在Java中检查重复项 //此代码允许计算机从数组中选择第一个随机数 int rn1=boarduser[new Random().nextInt(boarduser.length)]; System.out.println(“计算机值:+rn1”); //此代码允许计算机从数组中选择第二个随机数 int rn2=boarduser[new Random().nextInt(boarduser.length)]; System.out.println(“计算机值:+rn2”); 布尔标记重复1;//检查计算机是否两次采用相同的值 对于(int j=0;j,java,arrays,loops,Java,Arrays,Loops,首先,我想说我对Java的知识有限,所以这里就是 代码仍然不完整,但我要做的是检查在boarduser中选择的随机变量是否与上一个值相同。如果是,我希望它在我的boarduser数组中选择另一个变量,直到它与上一个变量不相同。只需保留(re)选择第二个值,直到它与第一个值不一致 // This code lets the computer select the first random number from your array int rn1 = boarduser[new Random()
boarduser
中选择的随机变量是否与上一个值相同。如果是,我希望它在我的boarduser
数组中选择另一个变量,直到它与上一个变量不相同。只需保留(re)选择第二个值,直到它与第一个值不一致
// This code lets the computer select the first random number from your array
int rn1 = boarduser[new Random().nextInt(boarduser.length)];
System.out.println("Computer's Value: " + rn1);
// This code lets the computer select the second random number from your array
int rn2 = boarduser[new Random().nextInt(boarduser.length)];
System.out.println("Computer's Value: "+ rn2);
boolean tokenduplicate1; // check if the computer took the same value twice
for (int j = 0; j < i; ++j) {
if (rn2 == rn1) {
tokenduplicate1 = true;}
while (tokenduplicate1);
// This code lets the computer select the third random number from your array
int rn3 = boarduser[new Random().nextInt(boarduser.length)];
System.out.println("Computer's Value: "+ rn3);
boolean tokenduplicate2; // check if the computer took the same value twice
for (int k = 0; k < i; ++k) {
if (rn3 == rn1 || rn3 == rn2) {
tokenduplicate1 = true;}
while (tokenduplicate1);
可以使用集合,然后检查其长度
int rn1 = boarduser[new Random().nextInt(boarduser.length)];
System.out.println("Computer's Value: " + rn1);
int rn2 = boarduser[new Random().nextInt(boarduser.length)];
while(rn2 == rn1)
{
rn2 = boarduser[new Random().nextInt(boarduser.length)];
}
System.out.println("Computer's Value: " + rn2);
int-somevalue=3;//如果需要3个值
Set number=新的LinkedHashSet();
while(number.size()!=somevalue){
add(new Random().nextInt(boarduser.length));
}
系统输出打印项次(数字);
打印例如:[11,1,5]我认为您应该阅读一些基本代码教程,
while(1)
至少看起来很奇怪,我知道,这还不完整,这是我试图创建一个循环来选择另一个随机整数rn2,但如果你想消除重复项,它就不起作用。如果你想消除重复项,Java的集合是一个好主意,因为它们的内置功能是不包含重复项。我发布了一个答案,它使用集合。NB:如果boarduser
只包含相等的值,则会导致无限循环。实际上,生成boarduser
时,不会出现重复的数字!!因此这确实很有帮助!谢谢!如果没有重复的数字,只需将数组洗牌,然后先取N
int somevalue = 3; // if you want 3 values
Set<Integer> numbers = new LinkedHashSet<Integer>();
while(numbers.size() != somevalue) {
numbers.add(new Random().nextInt(boarduser.length));
}
System.out.println(numbers);