2017-02-08 75 views
-3

对于我的任务,我们被要求添加一个手册IndexOutOfBoundsException。抛出异常

public int get(Object[] objArr){ 
    size = objArr.length; 
    for(int i = 0; i < size; i++) 
     if(objArr[i] < 0 || objArr[i] > objArr.length) 
     { 
      throw new IndexOutOfBoundsException("I must be greater than 0 and less than " + size); 
     } 

我试图通过望得到的代码回路和检查小于0的数字和他们的指数是由用户声明数组之外。我的if语句出错了,想知道如何解决这个问题。

if(i < 0 || i >= objArr.length) 
+4

* “我得到一个错误” * - 什么样的错误?可能你不能比较'Object'和'int'?! – luk2302

+2

您似乎将数组中的“i”索引与该数组中的值“objAr [i]”混淆。 –

+0

你能告诉我这将如何编译if(objArr [i] <0 || objArr [i]> objArr.length) –

回答

0

你有你的时候抛出异常:

+1

它应该是'i> =大小'@xander提 – Absolut

+0

是的,这是正确的,编辑 – Zeromus

0

拳,你进入了循环,第二你需要检查的指标,而不是对象的索引值之前,你应该抛出的厚望得到一个输入索引i,即< 0或>大于数组的大小。

像:

public void get(Object[] objArr, Integer i){ 
    size = objArr.length; 
    if(i<0 || i >= size){ 
     throw new IndexOutOfBoundsException("I must be greater than 0 and less than " + size); 
    } 
}