如何在原始数组长度小于新数组固定长度时避免出现“OutOfBounds错误”?

huangapple go评论70阅读模式
英文:

How do I avoid this OutOfBounds Error when an original array is less than the fixed length of a new array?

问题

对于我正在处理的任务,我有两个初始化的数组:

private int[] numbers;
numbers = new int[] {2, 3, 1, 4, 7, 6, 5, 2}
private int[] newNumbers = new int[8];

这样做的效果是,我有一个 For 循环,将原始 numbers 数组中的数字赋值给 newNumbers 数组。

Numbers 数组的长度可以不同,最多有 24 个数字,最少有 1 个数字。

我编写了一段代码,无论 numbers 数组的长度如何,都会将数字分割到 newNumbers 数组中,而 newNumbers 数组的长度始终为 8。

当有八个或更多数字时,我已经使其正常工作;然而,当我使用 For 循环在数字少于 8 个时尝试进行分割时,我会得到数组越界错误。

我使用的 For 循环(对于前 8 个数字,接下来的 8 个数字以及再接下来的 8 个数字,它们各自使用不同的循环)是:

for (int i = 0; i < this.newNumbers.length; i++)
{
    this.newNumbers[i] = this.numbers[i];
}

它在需要时按预期工作,但是当数字少于 8 个时,我会得到一个越界数组错误。我不确定是否是因为第二个数组的长度固定为 8,但我认为在这里更有经验的 Java 程序员可能能够提供一些建议。

英文:

For this task I'm working on I have two arrays initialised:

private int[] numbers;
numbers = new int[] {2, 3, 1, 4, 7, 6, 5, 2}
private int[] newNumbers = new int[8];

What happens with this is that I've got a For Loop that assigns the numbers from the original numbers array into the newNumbers array.

The Numbers array can vary in length with a maximum of 24 numbers and minimum of 1 number..

I've got code written that will divide the numbers (no matter the length of the numbers array) into the newNumbers array and the newNumbers array will always have a fixed length of 8.

I've got it working for dividing the numbers when there are eight numbers or more however when I use my For Loop to try and divide the numbers when there are less than 8 I get an out of bounds error.

The For Loop I'm using (for the first 8 numbers, the next 8 and the 8 after that use their own loops) is:

for (int i = 0; i &lt; this.newNumbers.length; i++)
	{
		this.newNumbers[i] = this.numbers[i];
	}

It works as needed except for when there are less than 8 numbers and I'll just get an OutOfBounds array. I'm not sure whether that's due to the second array having a fixed length of 8 or not but I thought the more experienced Java programmers here would be able to offer some advice.

答案1

得分: 1

ArrayIndexOutOfBoundsException表示数组已使用非法索引进行访问。

在您的情况下,数组numbers通过超过其长度的索引进行访问。

正如评论中所提到的,您只需要检查索引i是否超出了numbers数组的范围。以下是您可以实现这一点的方式:

int[] numbers = new int[] { 1, 2, 3, 4 };
int[] newNumbers = new int[8];

for (int i = 0; i < newNumbers.length; i++) {
    if (i < numbers.length) {
        newNumbers[i] = numbers[i];
    } else {
        newNumbers[i] = 0;
    }
}
System.out.println(Arrays.toString(newNumbers));

输出结果为:

[1, 2, 3, 4, 0, 0, 0, 0]
英文:

> ArrayIndexOutOfBoundsException indicates that an array has been
> accessed with an illegal index.

In your case the array numbers is accessed by an index greater then its length.

As mentioned in the comments you just need to check that the index i doesn't overflow the numbers array. This is how you can do it:

int[] numbers = new int[] { 1, 2, 3, 4 };
int[] newNumbers = new int[8];

for (int i = 0; i &lt; newNumbers.length; i++) {
    if (i &lt; numbers.length) {
        newNumbers[i] = numbers[i];
    } else {
        newNumbers[i] = 0;
    }
}
System.out.println(Arrays.toString(newNumbers));

The output is:

[1, 2, 3, 4, 0, 0, 0, 0]

答案2

得分: 0

数组始终需要静态大小。如果数组大小小于8,您将始终需要用零填充数组。

我建议您尝试在Java中使用List。

List<Integer> newNumbers = new ArrayList();
int maxSize = 8;
for(int i=0; i<numbers.length; i++){
     newNumbers.add(numbers[i]);
     if(newNumbers.size() == maxSize){
          break;
     }
}

List更具动态性。如果您正在处理仅接受数组的方法,那么您总是可以将列表转换回数组。

英文:

Arrays always need a static size. You will always need to pad the arrays with zeroes if size of arrays is less than 8.

I suggest you try using List in java.

List&lt;Integer&gt; newNumbers = new ArrayList();
int maxSize = 8;
for(int i=0;i&lt;numbers.length;i++){
     newNumbers.add(numbers[i]);
     if(newNumbers.size()==maxSize){
          break;
     }
}

List is more dynamic. If you are dealing with a method that accepts array only then you can always convert the list back to array.

答案3

得分: 0

一种解决方案是,只需循环遍历数字数组的长度,而不是遍历newNumbers数组,这将用0填充newNumbers数组的其余部分:

for (int i = 0; i < numbers.length; i++)
{
  newNumbers[i] = numbers[i];
}

另一种选项是使用arraycopy:

System.arraycopy(numbers, 0, newNumbers, 0, shortNumbers.length);

这里的0是每个数组的起始位置,其中numbers是目标数组,numbers是要复制的数组。
这比Java中的等效循环写法要快得多。

英文:

One solution is just to loop over the numbers array length rather than the newNumbers array as this will pad the rest of the newNumbers array with 0s:

for (int i = 0; i &lt; numbers.length; i++)
  {
    newNumbers[i] = numbers[i];
  }

Another option is to use arraycopy:

System.arraycopy(numbers, 0, newNumbers, 0, shortNumbers.length);

Here the 0s are the start positions of each array where numbers is the destination and numbers is the array to be copied.
This is the much faster than the equivalent loop written out longhand in Java.

huangapple
  • 本文由 发表于 2020年8月29日 14:23:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63644089.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定