用java两种策略写数组随机储存一堆箱子的质量,直到装不下
时间: 2023-12-03 07:43:29 浏览: 29
策略一:使用ArrayList
首先,我们需要创建一个ArrayList来储存箱子的质量。然后,我们可以使用Random类生成随机数来表示箱子的质量,并将其添加到ArrayList中,直到装不下为止。
代码示例:
```java
import java.util.ArrayList;
import java.util.Random;
public class BoxStorage {
public static void main(String[] args) {
int MAX_CAPACITY = 100; // 最大承载量
int currentCapacity = 0; // 当前承载量
ArrayList<Integer> boxList = new ArrayList<>(); // 储存箱子质量的ArrayList
Random rand = new Random();
while (currentCapacity < MAX_CAPACITY) {
int boxWeight = rand.nextInt(50) + 1; // 生成1-50之间的随机数作为箱子的质量
if (currentCapacity + boxWeight > MAX_CAPACITY) {
break; // 当箱子质量超过最大承载量时跳出循环
}
boxList.add(boxWeight); // 将箱子质量添加到ArrayList中
currentCapacity += boxWeight; // 更新当前承载量
}
// 输出箱子质量
System.out.println("箱子质量:");
for (int i = 0; i < boxList.size(); i++) {
System.out.print(boxList.get(i) + " ");
}
}
}
```
策略二:使用数组
同样,我们可以使用一个数组来储存箱子的质量。需要注意的是,我们需要提前确定数组的长度,因为数组的长度是不可变的。
代码示例:
```java
import java.util.Random;
public class BoxStorage {
public static void main(String[] args) {
int MAX_CAPACITY = 100; // 最大承载量
int currentCapacity = 0; // 当前承载量
int[] boxArray = new int[10]; // 储存箱子质量的数组
Random rand = new Random();
for (int i = 0; i < boxArray.length; i++) {
int boxWeight = rand.nextInt(50) + 1; // 生成1-50之间的随机数作为箱子的质量
if (currentCapacity + boxWeight > MAX_CAPACITY) {
break; // 当箱子质量超过最大承载量时跳出循环
}
boxArray[i] = boxWeight; // 将箱子质量添加到数组中
currentCapacity += boxWeight; // 更新当前承载量
}
// 输出箱子质量
System.out.println("箱子质量:");
for (int i = 0; i < boxArray.length; i++) {
if (boxArray[i] == 0) { // 数组中的0表示未储存箱子
break;
}
System.out.print(boxArray[i] + " ");
}
}
}
```