所以我有问题从arraylist中打印出一个随机选择的元素,然后打印更新的arraylist而没有随机元素。每次我打印更新的列表时,它会给我arraylist减去随机选择的元素并减去另一个元素。
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;
public class LabPartyGuests {
public static void main(String[] args) {
int numberOfGuests = 4;
Scanner input = new Scanner(System.in);
Random rand = new Random();
ArrayList<String> guestList = new ArrayList<String>();
System.out.println("Please enter 4 guests: ");
System.out.print("guest1: ");
String guest1 = input.nextLine();
System.out.print("guest2: ");
String guest2 = input.nextLine();
System.out.print("guest3: ");
String guest3 = input.nextLine();
System.out.print("guest4: ");
String guest4 = input.nextLine();
for (int i = 0; i <= 0; i++) {
guestList.add(guest1);
guestList.add(guest2);
guestList.add(guest3);
guestList.add(guest4);
}
System.out.println();
System.out.print("Guest list: " + guestList);
System.out.println();
guestList.remove(rand.nextInt(4));
System.out.printf("%s can't come %n", guestList.remove(rand.nextInt(4)));
for (int i = 0; i < guestList.size(); i++) {
guestList.size();
}
System.out.print(guestList);
}
}
答案 0 :(得分:1)
您要删除两个元素:
guestList.remove(rand.nextInt(4)); // one
System.out.printf("%s can't come %n", guestList.remove(rand.nextInt(4))); // two
如果要打印已删除的元素,请存储第一个删除的输出,而不是两次调用remove:
String removed = guestList.remove(rand.nextInt(4));
System.out.println("removed element " + removed);