Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.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 我一直有一种感觉,我不知道为什么_Java - Fatal编程技术网

Java 我一直有一种感觉,我不知道为什么

Java 我一直有一种感觉,我不知道为什么,java,Java,我一直在下面的行中获取ArrayIndexOutOfBoundsException winVals[i]=rand,但我不知道为什么 int valueCount = 5; int theLimit = 5; int[] winVals = new int[valueCount]; Random r = new Random(); int rand = 0; for(int i= 0; i < winVals.length; i++) { rand = r.nextInt(theL

我一直在下面的行中获取
ArrayIndexOutOfBoundsException
winVals[i]=rand
,但我不知道为什么

int valueCount = 5;
int theLimit = 5;
int[] winVals = new int[valueCount];
Random r = new Random();
int rand = 0;
for(int i= 0; i < winVals.length; i++)
{
    rand = r.nextInt(theLimit - 1) +1;
    if(i == 0)
    {
        winVals[0] = rand;
    }
    else if (i > 0)
    {
        for (int j = 0; j < winVals.length; j++)
        { 
           if( winVals[j] == rand)
           {
              i--;
           }      
           else
           {
               winVals[i] = rand;
           }
        }
    }
}
for(int i=0; i < valueCount; i++)
{
    System.out.println(winVals[i]);
}
int valueCount=5;
int-theLimit=5;
int[]winVals=新的int[valueCount];
随机r=新随机();
int rand=0;
对于(int i=0;i0),则为else
{
对于(int j=0;j
在循环内递减循环计数器:

if( winVals[j] == rand)
     i--;
这会导致越界。

for(int j=0;jfor (int j = 0; j < winVals.length; j++)
{ 
   if( winVals[j] == rand)
       i--;
   else
   {
       winVals[i] = rand;
   }
}
{ 如果(winVals[j]==rand) 我--; 其他的 { winVals[i]=兰特; } }
在本节中,您将循环使用
j
的值和减少
i
,但您不必费心检查
i
是否仍然有效。如果
i
为1,您将其减少两次会怎么样?

我认为这行就是问题所在

   if( winVals[j] == rand)
     i--;

如果在这条线之前,i=0和j=0,并且这个条件变为真,i变为-1刚刚测试了它,因为上面提到的指数是递减的,这是一个无止境的循环。

您是否尝试在该点打印出
i
的值?减少循环体中
for
循环计数器的
。通常这不是一个好主意……而且,在循环中,我不会更改正在增加的变量的值;虽然它可能是合法的,但它不是很常用,也很难被其他程序员注意到,我会在这些情况下使用
while
(IMHO)