简体   繁体   English

删除Java中的数组值将返回OutOfBoundsException

[英]Deleting Array Values in Java Returns OutOfBoundsException

I am a computer science student in high school, and I was given a project where I have to create a program that can add the values of an integer array, count the number of values contained in the array, and remove every instance of a value in that array. 我是一名高中计算机科学专业的学生,​​我获得了一个项目,在这个项目中,我必须创建一个程序,该程序可以添加整数数组的值,计算数组中包含的值的数量,并删除每个值实例在那个数组中。

Here is the code, separated into three methods for each function described above: 这是代码,针对上述每个功能分为三种方法:

import java.lang.System;
import java.lang.Math;
import java.util.Arrays;

public class ArrayFunHouse
{
//instance variables and constructors could be used, but are not really needed

//getSum() will return the sum of the numbers from start to stop, not including stop
public static int getSum(int[] numArray, int start, int stop)
{
    int count = start;
    int output = 0;
    while(count<=stop)
    {
        output = output + numArray[count];
        count++;
    }
    return output;
}

//getCount() will return number of times val is present
public static int getCount(int[] numArray, int val)
{
    int x = 0;
    int count = 0;
    while(x<numArray.length)
    {
        if(val==numArray[x])
            count++;
        x++;
    }
    return count;
}

public static int[] removeVal(int[] numArray, int val)
{
    int[] newArray = new int[ numArray.length - getCount(numArray, val) ];
    int x = 0;
    for(int position = 0; position < numArray.length; position++)
    {
        x = numArray[position];
        if(x!=val)
        {
            newArray[position] = numArray[position];
        }
    }
    return newArray;
}
}

And here is the runner designed to execute the code, including the sample data we were instructed to use: 这是设计用于执行代码的运行器,其中包括指示我们使用的示例数据:

import java.util.Arrays;

public class ArrayFunHouseRunner
{
public static void main( String args[] )
{
    int[] one = {7, 4, 10, 0, 1, 7, 6, 5, 3, 2, 9, 7};

    ArrayFunHouse test = new ArrayFunHouse();

    System.out.println(Arrays.toString(one));
    System.out.println("sum of spots 3-6  =  " + ArrayFunHouse.getSum(one,3,6));
    System.out.println("sum of spots 2-9  =  " + ArrayFunHouse.getSum(one,2,9));
    System.out.println("# of 4s  =  " + ArrayFunHouse.getCount(one,4));
    System.out.println("# of 9s  =  " + ArrayFunHouse.getCount(one,9));
    System.out.println("# of 7s  =  " + ArrayFunHouse.getCount(one,7));
    System.out.println("new array with all 7s removed  =  " + test.removeVal(one,7));
    System.out.println("# of 7s  =  " + ArrayFunHouse.getCount(ArrayFunHouse.removeVal(one,7),7));

    int[] two = {4,2,3,4,6,7,8,9,0,10,0,1,7,6,5,3,2,9,9,8,7};

    //add test cases


}
}

When I run the code, the following is output: 当我运行代码时,将输出以下内容:

[7, 4, 10, 0, 1, 7, 6, 5, 3, 2, 9, 7]
sum of spots 3-6  =  14
sum of spots 2-9  =  34
# of 4s  =  1
# of 9s  =  1
# of 7s  =  3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at ArrayFunHouse.removeVal(ArrayFunHouse.java:49)
at ArrayFunHouseRunner.main(ArrayFunHouseRunner.java:21)

Process completed.

As shown above, the code runs smoothly until it reaches the third method. 如上所示,代码运行平稳,直到到达第三种方法为止。 What do I need to fix in order to get the code to run smoothly, as indicated by the error message? 如错误消息所示,我需要解决什么才能使代码平稳运行?

In your removeVal function you are trying to set the index of the new array as the same index it had in the old array. 在您的removeVal函数中,您尝试将新数组的索引设置为与旧数组中相同的索引。 As arrays get smaller, it can't place key 9 in an 8 item array. 随着数组变小,无法将键9放入8项数组中。

Change it to this: 更改为此:

 int newPosition = 0;// outside of loop

    x = numArray[position];

    if(x!=val)
    {
        newArray[newPosition] = numArray[position];
        newPosition++;
    }
for(int position = 0; position < numArray.length; position++)
{
    x = numArray[position];
    if(x!=val)
    {
        newArray[position] = numArray[position];
    }
}

You can't use position to access both the target array and the source array. 您不能使用position来访问目标数组和源数组。 You need two variables, one of which isn't incremented if x == val . 您需要两个变量,如果x == val ,则其中一个变量不会递增。

I think it's because of this line: newArray[position] = numArray[position]; 我认为是因为这一行: newArray[position] = numArray[position]; . Since newArray is shorter than numArray , numArray will have position indices that are out of bounds for numArray . 由于newArraynumArray短,因此numArray位置索引超出numArray的范围。 You'd probably want two position values, say "newArPos" and "numArPos", and you don't increment "newArPos" if you're excluding a value. 您可能需要两个位置值,例如“ newArPos”和“ numArPos”,并且如果要排除一个值,则不要递增“ newArPos”。

In your removeVal method you create a new array that is smaller then the original one. 在removeVal方法中,创建一个比原始数组的新数组。 But in your for loop you loop through a number of times equal to the original larger array. 但是在for循环中,循环的次数等于原始的较大数组的次数。 Make sure in your loop you don't access the new smaller array in a spot that only exists in the original array. 确保在循环中,您不会在仅存在于原始阵列中的位置访问新的较小阵列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM