从索引到n的数组返回值?

时间:2014-03-07 04:45:54

标签: java arrays indexoutofboundsexception

我只想创建一个方法,它将返回从索引到index + n的数组值。例如 - 索引3和n的4应该返回值

//Array[3]
//Array[4]
//Array[5]
//Array[6]
//Array[7]

public int[] subSequence(int index, int n, int[] array) {
int[] valuelist = new int[array.length];
    for(int i = index; i <= n + index; i++)
    {
        if((index + n) <= array.length)
        valuelist[i] = array[i];
    }
   return valuelist;

}

我很抱歉发布了这样一个愚蠢的问题,但我是新手,并且找不到类似的问题。

我的问题:我正在接受ArrayIndexOutOfBounds我正在做的事情,而且我并不知道如何解决这个问题。

5 个答案:

答案 0 :(得分:1)

这可能会对你有帮助,

   for(int i = n; i <=( n + index); i++)
    {

         if( i >=array.length){//check length of array with index,n

          break;
         }
     else{
        valuelist[i] = array[i];
        }
    }

答案 1 :(得分:0)

  1. Google ArrayIndexOutOfBounds
  2. 阅读第一个链接(异常的JavaDoc:http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
  3.   

    抛出表示已使用非法访问数组   指数。该指数为负数或大于或等于   数组的大小。

答案 2 :(得分:0)

你有:

for(int i = index; i <= n + index; i++)

你可能意味着:

for(int i = index; i < n + index; i++)

我假设index是起始索引,n应该是计数。在您当前的实施中,使用<=,请考虑以下情况:

int[] a = new int[50];
int[] b = subSequence(0, 50, a);

你会想象这会有效,但你的循环会和i <= 0+50一样长,这意味着在i==50,这超出了数组的末尾(数组中的最后一个索引)是49)。

另一个问题是:

if((index + n) <= array.length)
    valuelist[i] = array[i];

这看起来像是在尝试将索引保留在边界内。仔细检查if语句,因为这不是它正在做的事情。

答案 3 :(得分:0)

if((index + n) <= array.length)这行代码是java.lang.ArrayIndexOutOfBoundsException的问题。

代码表示如果 index + n小于或等于数组的长度,则执行if语句中的语句。现在,当index+n等于数组的长度时,尝试在此语句中为数组设置值时会出现ArrayIndexOutOfBoundsException valuelist[i] = array[i];

要避免ArrayIndexOutOfBoundsException,请尝试:

if((index + n) < array.length)

此代码删除了equals条件,只有在表达式index + n小于数组长度时才会执行。 :D

要记住的重要一点是,数组在访问时从零开始。但是,数组的length属性不是零。因此,如果代码尝试使用length属性访问数组元素,则会抛出此运行时异常,即ArrayIndexOutOfBoundsException。这是因为代码试图访问一个元素传递给数组末尾的元素。

示例:

int [] x = {0, 1}; // x.length = 2 and 1 is at position 1 and 0 is at position 0
System.out.println(x[x.length]); //throws ArrayIndexOutOfBoundsException
System.out.println(x[0]); // prints the first element 0

快乐编码。

答案 4 :(得分:-3)

如果你不知道数组的大小,最好使用arraylist或其他一些固定大小的集合类。之后,将其转换为数组或按原样使用它。