Remove random index from array List

I have an ArrayList of 4 elements. I need to delete one element randomly and display the updated ArrayList. However, my random object retains targeting for the second and third elements in the array list. As far as I understand, my random case would be this: 0 1 2 3. Is this not enough to cover my 4 elements? Why does it support targeting the same indexes? I tried to increase the random number (4) + 1, but that takes me beyond.

Random rand = new Random();
Scanner input = new Scanner(System.in);
int numberOfGuests = 4;
ArrayList<String> guestList = new ArrayList<>(4); 
System.out.println("Enter 4 guests:");

for(int i = 1; i <=numberOfGuests; i++){
    System.out.printf("guest%d: ", i);
    guestList.add(input.nextLine());
}
System.out.println("Guest List: " + guestList);
String remove = guestList.remove(rand.nextInt(4)); 
System.out.printf("%s can't come%n" , remove);   
System.out.println("Guest List: " + guestList);
+4
source share
1 answer

yoy checks when you produce an arbitrary number of users, the rage level is set to the length of the array minus one, for example, in your case

String remove = guestList.remove(rand.nextInt(3)); 
0

Source: https://habr.com/ru/post/1660464/


All Articles