Java – delete random index from ArrayList

I have a 4-item ArrayList I need to randomly delete an item and display the updated ArrayList However, my random number continues to target the second and third elements in the array list As far as I know, my random number will be like this: 0 1 2 3 Isn't that enough to cover my four elements? Why does it continue to target the same index? I tried increasing the random number (4) 1, but it pushed me beyond the limit

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);

Solution

Yoy check when you use random number generation, rage is set to the length of the array minus one, for example, in your case

String remove = guestList.remove(rand.nextInt(3));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>