问题描述
对于给定的低于code后的46348我得到 ArrayIndexOutOfBoundsException异常
INT输入值。我给定的条件在的为的循环,保持数组的限制条件。但不知何故,我得到这个例外,我无法弄清楚。我的要求是找到如下号码的所有primenumbers。
for the Given below code after int Input Value of 46348 i am getting ArrayIndexOutOfBoundsException
. I am given Condition in for loop that keeps the array limits. But somehow i am getting this exception and i unable to figure it out. And my requirement is find all primenumbers below given number.
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
int[] arr= new int[n+1];
for(int i=2;i<=n;i++)
{
if(arr[i]==0)
{
for(j=i;j*i<=n;j++)
arr[j*i]=1; // Here i am getting Exception
}
}
输入:
46349
输出:
java.lang.ArrayIndexOutOfBoundsException:-2146737495
java.lang.ArrayIndexOutOfBoundsException: -2146737495
502802
感谢。
推荐答案
您已经遇到了一个算术溢出。
You have encountered an arithmetic overflow.
在Java中, INT
数据类型是一个32位有符号整数,这意味着它可以-2147483648和2147483647之间的值。
In Java, int
data type is a 32-bit signed integer, which means it can have values between -2147483648 and 2147483647.
在这一行:
for(j=i;j*i<=n;j++)
如果 I
是46349则Ĵ
变得46349,太。如果通过46349乘以46349,将得到2148229801,比2147483647更大,所以整数溢出并变为-2146737495。当然,它小于46349,所以在在检查
-loop通行证。但是,你不能索引在Java负值的数组,这就是为什么你得到 ArrayIndexOutOfBoundsException异常
。
If i
is 46349 then j
becomes 46349, too. If you multiply 46349 by 46349, you get 2148229801, which is greater than 2147483647, so the integer overflows and becomes -2146737495. Naturally, it is less than 46349, so the check in the for
-loop passes. But you cannot index an array with a negative value in Java, that's why you get the ArrayIndexOutOfBoundsException
.
范围检查你的输入值 N'LT; 46340
,或者如果它真的需要与 N = 46349
输入,工作切换到长
数据类型,这将工作到 N = 3037000499
。
Range check your input value for n < 46340
, or if it really needs to work with n = 46349
input, switch to long
data type, which will work up to n = 3037000499
.
这篇关于获得ArrayIndexOutOfBoundsException异常某一输入值之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!