2017-01-12 4 views
0

Я студент-информатик в старшей школе, и мне был предоставлен проект, где мне нужно создать программу, которая может добавлять значения целочисленного массива, подсчитать количество значений, содержащихся в массив и удалить каждый экземпляр значения в этом массиве.Удаление значений массива в Java Возвращает OutOfBoundsException

Вот код, разделены на три метода для каждой функции, описанные выше:

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; 
} 
} 

А вот бегунок предназначен для выполнения кода, включая данные выборки мы были проинструктированы использовать:

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 


} 
} 

Когда я запускаю код, следующий выход:

[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. 

Как показанный выше, код работает плавно, пока не достигнет третьего метода. Что мне нужно исправить, чтобы заставить код работать бесперебойно, как указано сообщением об ошибке?

ответ

0

В вашей функции removeVal вы пытаетесь установить индекс нового массива как тот же самый индекс, который он имел в старом массиве. Поскольку массивы становятся меньше, он не может поместить ключ 9 в массив из 8 элементов.

Изменить его к этому:

int newPosition = 0;// outside of loop 

    x = numArray[position]; 

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

Вы не можете использовать position для доступа как целевой массив и массив источников. Вам нужны две переменные, одна из которых не увеличивается, если x == val.

0

Я думаю, что из-за этой линии: newArray[position] = numArray[position];. Поскольку newArray короче numArray, numArray будет иметь индексы позиций, которые находятся за пределами поля для numArray. Вероятно, вам нужны два значения позиции, например «newArPos» и «numArPos», и вы не увеличиваете «newArPos», если вы исключаете значение.

-1

В вашем методе removeVal вы создаете новый массив, который является меньшим, а затем оригинальным. Но в вашем цикле for вы циклически повторяетесь в несколько раз, сравнивая исходный массив большего размера. Убедитесь, что в цикле вы не получаете доступ к новому меньшему массиву в месте, которое существует только в исходном массиве.

Смежные вопросы