java – 从arrayList中删除随机索引
发布时间:2020-12-15 02:17:27 所属栏目:Java 来源:网络整理
导读:我有一个4项的ArrayList.我需要随机删除一个项目并显示更新的ArrayList.然而,我的随机数继续瞄准数组列表中的第二个和第三个元素.据我所知,我的随机数会像这样:0 1 2 3.这不足以覆盖我的4个元素吗?为什么它会继续针对相同的索引?我试过增加随机数(4)1,但
我有一个4项的ArrayList.我需要随机删除一个项目并显示更新的ArrayList.然而,我的随机数继续瞄准数组列表中的第二个和第三个元素.据我所知,我的随机数会像这样:0 1 2 3.这不足以覆盖我的4个元素吗?为什么它会继续针对相同的索引?我试过增加随机数(4)1,但这让我超出界限.
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); 解决方法
yoy检查当你使用随机数生成时,rage被设置为数组的长度减去一个,例如你的情况
String remove = guestList.remove(rand.nextInt(3)); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |