gpt4 book ai didi

java - 我的随机搜索出了什么问题?

转载 作者:行者123 更新时间:2023-12-02 06:17:05 24 4
gpt4 key购买 nike

我收到错误:“ArrayIndexOutOfBounds Exception3”我不认为这是唯一的错误,但到目前为止这就是我所能弄清楚的。

import java.util.Random;
/*class containing random search algorithm*/
public class RandomSearch {
public static int randomSearch(int queryValue, int[] list) {
/*conducts a random search as specified by user*/
/*trys 10,000,000 random combinations searching
for user value*/
int length = list.length;
for(int i=0; i < 10000000; i++) {
/*generates a random number from 0 to length*/
int randomNum = (int)Math.floor(Math.random()*(length+1));
StdOut.print(randomNum);
if((int)queryValue == (int)list[randomNum]) {
return randomNum;
}
}
/*returns -2 if user value not found*/
return -2;
}
}

最佳答案

您需要这样的东西来生成索引,这给出了 0 和长度之间的索引您生成的索引超出了数组的大小,这就是您收到索引越界异常的原因。

/*Edit - Changed val to length to match the question.*/
public int randInt(int length) {

// Usually this can be a field rather than a method variable
Random rand = new Random();
int randomNum = rand.nextInt(length);
return randomNum;
}

关于java - 我的随机搜索出了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21356262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com