编写几种数组操作方法。一种方法将总结一部分 提供数组,另一种方法将计算数组中出现的特定数量的多少,以及最后一个 方法将从数组中删除所有特定值。
我已经完成了代码,但是我退出了反弹:9错误,我无法解决它。
import java.lang.System;
import java.lang.Math;
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 sum = 0;
int[] locArray = numArray;
for(int i = start; i<=stop; i++)
{
sum+=locArray[i];
}
return sum;
}
// getCount() will return number of times val is present
public static int getCount(int[] numArray, int val)
{
int times = 0;
for (int i : numArray)
{
if (i == val)
times++;
}
return times;
}
public static int[] removeVal(int[] numArray, int val)
{
int[] array = new int[numArray.length - getCount(numArray, val)];
byte index = 0;
for (int i : numArray)
{
if (i != val) {
array[index] = i;
index++;enter code here
}
}
return array;
}
}
我的跑步者班级
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};
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));
one = ArrayFunHouse.removeVal(one, 7);
System.out.println("new array with all 7s removed = " +
Arrays.toString(one));
System.out.println("# of 7s = " + ArrayFunHouse.getCount(one, 7));
System.out.println();
int[] two = {7, 4, 2, 7, 3, 4, 6, 7, 8, 9, 7, 0, 10, 7, 0, 1, 7, 6, 5, 7, 3, 2, 7, 9, 9, 8,7};
System.out.println(Arrays.toString(one));
System.out.println("sum of spots 3-16 = " +
ArrayFunHouse.getSum(one,3,16));
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));
one = ArrayFunHouse.removeVal(one, 7);
System.out.println("new array with all 7s removed = " +
Arrays.toString(one));
System.out.println("# of 7s = " + ArrayFunHouse.getCount(one, 7));
}
}
我的输出
[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
new array with all 7s removed = [4, 10, 0, 1, 6, 5, 3, 2, 9]
# of 7s = 0
[4, 10, 0, 1, 6, 5, 3, 2, 9]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at ArrayFunHouse.getSum(ArrayFunHouse.java:22)
at ArrayFunHouseRunner.main(ArrayFunHouseRunner.java:30)
我需要帮助。第一个工作正常,但第二个出错。
答案 0 :(得分:1)
在这行代码:ArrayFunHouse.getSum(one,3,16));
中,您将停止索引16传递给第一个数组,您需要做的是将其传递给第二个数组 2 即可。这是因为第一个数组的长度小于16.另外,在其他一些代码行中,你传入了一个,而不是传入两个。试试它是否有效。