62,620
社区成员
发帖
与我相关
我的任务
分享
import java.util.*;
public class Apple {
public static void main(String[] args) {
Random rd = new Random();
List<Integer> apples = new ArrayList<Integer>();
//随机生成取出的苹果的编号,并放入集合apples,也就是模拟题目中
//取苹果的操作。
int num;
for(int i=0; i<10; i++) {
num = rd.nextInt(20) + 1;//加1是为了防止出现编号为0的苹果
apples.add(num);
}
//第一次拿走苹果后,就从集合中删除,第二次从剩下的苹果中拿,
//第三次把剩下的全部拿走
int count;//拿走的苹果的编号
int[] arr = new int[apples.size()];//保存每一次拿走的苹果编号
int k;
for(int i=0; i<3; i++) {
if(i < 2) {//前两次拿苹果
num = rd.nextInt(apples.size() - 1);
for(int j=0; j<num; j++) {
count = rd.nextInt(num);
arr[j] = count;
System.out.println("第" + (i + 1) + "次拿出的苹果:" + apples.get(count)); //打印拿走的苹果编号
}
k = 0;
while(arr[k] != 0) {
apples.remove(arr[k]); //一次拿完后,从集中删除
k++;
}
} else {//第三次拿走剩下的苹果
for(int j=0; j<apples.size(); j++) {
count = apples.size() - 1;
System.out.println("第3次拿出的苹果:" + apples.get(count));
apples.remove(count);
}
}
}
}
}