Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从arrayList中删除随机索引_Java_Arrays_Random - Fatal编程技术网

Java 从arrayList中删除随机索引

Java 从arrayList中删除随机索引,java,arrays,random,Java,Arrays,Random,我有一个包含4项的ArrayList。我需要随机删除一项并显示更新的ArrayList。然而,我的random一直以数组列表中的第二个和第三个元素为目标。据我所知,我的随机数是这样的:01 2 3。这难道不足以涵盖我的4个要素吗?为什么它一直以相同的索引为目标?我已经尝试过增加随机数(4)+1,但这使我超出了范围 Random rand = new Random(); Scanner input = new Scanner(System.in); int numberOfGuests = 4;

我有一个包含4项的ArrayList。我需要随机删除一项并显示更新的ArrayList。然而,我的random一直以数组列表中的第二个和第三个元素为目标。据我所知,我的随机数是这样的:01 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);
Random rand=new Random();
扫描仪输入=新扫描仪(System.in);
int numberOfGuests=4;
ArrayList guestList=新的ArrayList(4);
System.out.println(“输入4个来宾:”);

对于(int i=1;iy)检查,当您使用随机数生成时,rage设置为数组长度减1,如您的情况

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

你的代码按原样复制在IntelliJ本地对我有效。你的代码对我有效。我使用4个预定义的来宾a、b、c和d在coderpad上运行了你的代码。我运行了10次,你可以看到它是有效的。链接在这里:你知道吗,伙计们,我的错。我必须运行15次以上才能得到所有的值,随机发生了ned在我运行它的前5次中一直选择相同的元素。我如何删除或关闭这个问题?在它被否决票屠杀之前。别担心,你发布了完全功能化、经过深思熟虑的代码。正如你所看到的,还没有人否决它。你可以删除它。
nextInt(n)
已经检查了从
0
n
的范围。因此您的答案只检查索引
0-2
,这是不正确的。顺便说一句,OP已经说他的代码按预期工作。