Java 什么';我的随机搜索有什么问题?
我得到了一个错误:“ArrayIndexOutOfBounds Exception 3”我不认为这是唯一的错误,但到目前为止,这是我能找到的全部Java 什么';我的随机搜索有什么问题?,java,Java,我得到了一个错误:“ArrayIndexOutOfBounds Exception 3”我不认为这是唯一的错误,但到目前为止,这是我能找到的全部 import java.util.Random; /*class containing random search algorithm*/ public class RandomSearch { public static int randomSearch(int queryValue, int[] list) { /*conducts
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;
}
}
import java.util.Random;
/*包含随机搜索算法的类*/
公共类随机搜索{
公共静态int随机搜索(int queryValue,int[]列表){
/*按用户指定进行随机搜索*/
/*尝试10000000个随机组合搜索
用户价值*/
int length=list.length;
对于(int i=0;i<10000000;i++){
/*生成从0到长度的随机数*/
int randomNum=(int)Math.floor(Math.random()*(长度+1));
标准输出打印(随机数);
if((int)queryValue==(int)list[randomNum]){
返回随机数;
}
}
/*如果未找到用户值,则返回-2*/
返回-2;
}
}
问题在于randomNum
可以获得大于可用于访问数组列表的最大索引的值
要解决这个问题,需要改变
int randomNum = (int) (Math.random() * (length + 1));
到
您需要这样的东西来生成索引,这会使索引介于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;
}
假设您的list.length
length是100,那么如果Math.random()
return0.999
,则此语句
(int)Math.floor(Math.random()*(length+1));
将返回100
。虽然100
超出了列表范围,但由于长度100
的数组的有效索引是从0
到99
答案已根据更新,数组索引从0开始,因此在数组上调用length()时,最后一个索引实际上是length-1。如果在列表[length-1]之后尝试任何索引,您将得到数组越界错误 尝试使用java.util.Random方法:
Random rand=new Random()代码>
int randomNum=rand.nextInt(长度+1)代码>
它给出了从1到长度的u数。标准方法是:
int randomNum = (int)(Math.random()*length);
您不需要Math.floor()
,因为强制转换到int
具有相同的效果
另外,只需乘以length
(而不是length+1
),就可以得到从0到length-1的数字
或者简单地使用JDK的API:
int randomNum = new Random().nextInt(length);
如果random()
返回1
,或者我遗漏了什么?不,我错了,1.0
不包括在内,正确的间隔是[0.0;1.0)
Math.random永远不能返回1我已将行更改为“int randomNum=(int)Math.floor(Math.random()*(length-1))”它消除了越界错误。该算法现在可以在所有情况下工作,除非queryValue是数组中的最后一个数字。示例queryValue=3,数组为[1,2,3]。我将其更改为“int randomNum=(int)Math.floor(Math.random()*(length)”,并且它可以工作。感谢所有帮助。
int randomNum = new Random().nextInt(length);