java实现从一个整型数组中随机取2个数,且两个数不能相同
时间: 2024-05-22 09:14:00 浏览: 16
可以使用Random类生成随机数,在保证两个数不相同的情况下,从数组中取出随机数。具体的实现方式如下:
int[] nums = {1, 2, 3, 4, 5, 6};
Random random = new Random();
int num1 = random.nextInt(nums.length);
int num2 = random.nextInt(nums.length - 1);
if (num2 >= num1) {
num2++;
}
int result1 = nums[num1];
int result2 = nums[num2];
这段代码会从数组中随机取出两个数字,并且保证这两个数字不同。
相关问题
java实现从一个整型数组中随机取2个数
可以用Random类来生成两个随机数,然后将数组中对应的两个元素交换位置,就可以实现从一个整型数组中随机取两个数了。具体实现可以参考如下代码:
```java
import java.util.Random;
public class RandomSelect {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
Random random = new Random();
int index1 = random.nextInt(nums.length);
int index2 = random.nextInt(nums.length);
// 交换两个元素的位置
int temp = nums[index1];
nums[index1] = nums[index2];
nums[index2] = temp;
System.out.println("随机选取的两个数为 " + nums[index1] + " 和 " + nums[index2]);
}
}
```
定义方法,实现将10个两位随机整数存入数组中Java
可以使用Java中的数组来存储一组整数。可以使用Math.random()来生成随机数。下面是一个示例代码来生成10个两位随机整数,并将它们存入一个数组中:
```
int[] arr = new int[10]; // 定义一个长度为10的整型数组
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 90 + 10); // 生成10到99之间的随机整数,并存入数组中
}
System.out.println(Arrays.toString(arr)); // 输出数组中的元素
```
在上述代码中,我们定义了一个长度为10的整型数组`arr`。然后使用for循环生成10个随机整数,并将它们存入数组中。最后使用`Arrays.toString()`方法输出数组中的元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)