Java If语句大于操作don';行不通
当编写语句来告诉程序中断或返回时,if语句仍然会在每次不满足条件时执行,并导致错误:java.lang.ArrayIndexOutOfBoundsException 我尝试过大于和等于,两者都有效。我检查了“>”在java中也是一个操作符。那为什么它仍然执行呢Java If语句大于操作don';行不通,java,if-statement,Java,If Statement,当编写语句来告诉程序中断或返回时,if语句仍然会在每次不满足条件时执行,并导致错误:java.lang.ArrayIndexOutOfBoundsException 我尝试过大于和等于,两者都有效。我检查了“>”在java中也是一个操作符。那为什么它仍然执行呢 public class adjacentElementsProduct { static int adjacentElementsProduct(int[] inputArray) { if(inputArray ==
public class adjacentElementsProduct {
static int adjacentElementsProduct(int[] inputArray) {
if(inputArray ==null|| inputArray.length<0) return 0;
int res=Integer.MIN_VALUE;
for( int i=0; i<inputArray.length;i++){
int stop=i+1;
if((i+1) > inputArray.length) break;
res=Math.max(res,inputArray[i]*inputArray[i+1]);
}
return res;
}
公共类邻接元素产品{
静态int邻接元素产品(int[]输入阵列){
如果(inputArray==null | | inputArray.length inputArray.length)中断;“”
不起作用,因此错误消息是:java.lang.ArrayIndexOutOfBoundsExceptionjava数组具有基于零的索引,因此长度为N的数组中的最后一个元素位于第(N-1)个元素
例如:int[]a={1,2,3}
,要访问元素3,我们将编写a[2]
或a[a.length-1]
在您的情况下,循环将转到i=inputArray.length-1
,因此如果调用inputArray[i+1]
,您将调用inputArray[inputArray.length]
这超出了范围。为了避免这种情况,您可以将循环结束条件修改为i
,也可以将if语句更改为
如果((i+1)>=inputArray.length)中断;
即使(i+1)==inputArray.length
,您将得到该异常。您在数组中访问的最高索引是inputArray.length-1
。基于i inputArray.length)break;
将永远不会为真,因此您将不会执行break;
。请仔细考虑一下,您真的需要该break吗条件?如果你想为我迭代一次更少的更改ipls upvote一次,我的问题不在“OfBoundsException”,而是在If((i+1)>inputArray.length)中断时它是如何工作的;我通过了他标记为重复的链接,它没有回答我的问题,这不是我的问题。当我看到inputArray时非常清楚[inputArray.length]。