用java实现随机生产三个数,直到三数之和不超过600
时间: 2023-06-05 09:08:11 浏览: 44
可以使用以下代码实现:
```java
import java.util.Random;
public class RandomSum {
public static void main(String[] args) {
Random rand = new Random();
int sum = 0;
int count = 0;
while(sum <= 600) {
int num = rand.nextInt(100);
System.out.println("生成的随机数为:" + num);
sum += num;
count++;
}
System.out.println("生成的三个数总和为:" + sum);
System.out.println("生成的随机数个数为:" + count);
}
}
```
这个程序使用Java中的Random类生成随机数,并不断随机生成三个数,直到这三个数之和超过了600。程序会输出每个随机数以及最终生成的三个数之和和生成的随机数个数。
相关问题
用java实现随机生产三个数,直到三数之和不超过600,并打印这三个数
可以使用如下Java代码实现:
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
int sum = 0;
int num1, num2, num3;
do {
num1 = rand.nextInt(600);
num2 = rand.nextInt(600);
num3 = rand.nextInt(600);
sum = num1 + num2 + num3;
} while (sum > 600);
System.out.println("随机生成的三个数分别为:" + num1 + "," + num2 + "," + num3);
}
}
```
当三数之和不超过600时,就会退出循环,并输出这三个数。
Java数组中抽取三个数随机组合
可以使用Java的Random类和数组来实现随机抽取三个数的组合。具体步骤如下:
1. 创建一个包含所有可能数的数组arr。
2. 使用Random类生成一个0到arr.length-1之间的随机数,取得arr中对应的数,将其从arr中删除。
3. 重复步骤2,直到抽取3个数,将它们存储在一个新的数组中。
下面是示例代码:
```java
import java.util.Arrays;
import java.util.Random;
public class RandomCombination {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] result = new int[3];
Random rand = new Random();
for (int i = 0; i < 3; i++) {
int index = rand.nextInt(arr.length);
result[i] = arr[index];
arr = removeElement(arr, index);
}
System.out.println(Arrays.toString(result));
}
private static int[] removeElement(int[] arr, int index) {
int[] newArr = new int[arr.length - 1];
for (int i = 0, j = 0; i < arr.length; i++) {
if (i != index) {
newArr[j] = arr[i];
j++;
}
}
return newArr;
}
}
```
在这个例子中,我们使用了removeElement方法来删除已经被抽取的数。这个方法在数组中删除给定索引的元素,然后返回一个新数组。最后,我们输出了随机组合的结果。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![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)