要生成自定义随机数1或-1,您需要使用nextBoolean()。首先,循环并在每次迭代中创建一个Random对象-for (int i = 0; i
Random rand = new Random();
}
现在,用于nextBoolean()在TRUE条件下生成ekse -1-for (int i = 0; i
Random rand = new Random();
if (rand.nextBoolean())
System.out.println(1);
else
System.out.println(-1);
}
示例import java.util.Random;
public class Demo {
public static void main(String[] args) {
for (int i = 0; i
Random rand = new Random();
if (rand.nextBoolean())
System.out.println(1);
else
System.out.println(-1);
}
}
}
输出结果1
-1
-1
-1
-1