Reputation: 45
So I'm having problem printing out a randomly chosen element from an arraylist and then printing the updated arraylist without that random element in it. Every time I print the updated list, it gives me the arraylist minus the randomly chosen element and minus another element.
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);
}
}
Upvotes: 0
Views: 955
Reputation: 394126
You are removing two elements :
guestList.remove(rand.nextInt(4)); // one
System.out.printf("%s can't come %n", guestList.remove(rand.nextInt(4))); // two
If you want to print the removed element, store the output of the first remove instead of calling remove twice :
String removed = guestList.remove(rand.nextInt(4));
System.out.println("removed element " + removed);
Upvotes: 1