Я студент-информатик в старшей школе, и мне был предоставлен проект, где мне нужно создать программу, которая может добавлять значения целочисленного массива, подсчитать количество значений, содержащихся в массив и удалить каждый экземпляр значения в этом массиве.Удаление значений массива в 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.
Как показанный выше, код работает плавно, пока не достигнет третьего метода. Что мне нужно исправить, чтобы заставить код работать бесперебойно, как указано сообщением об ошибке?