java - 索引越界异常但无法找出问题所在

标签 java arrays recursion arraylist

基本上,我必须接受用户输入,直到他们输入 0,然后找到数组中的最大值、负数数量以及正数之和。问题是我必须使用 array 并且不能使用 ArrayList 来调用其他方法,所以我想我应该创建一个 ArrayList 并使用其中的元素来创建一个数组,因为数组中存在未指定数量的元素。我一直将其视为错误,并尝试了我能想到的一切。请帮忙。

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
    at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    at java.util.ArrayList.get(ArrayList.java:322)
    at Assignment9.assignment9(Assignment9.java:37)
    at Assignment9.assignment9(Assignment9.java:49)
    at Assignment9.assignment9(Assignment9.java:49)
    at Assignment9.assignment9(Assignment9.java:49)
    at Assignment9.main(Assignment9.java:17)
<小时/>
//Class Description: Takes user input and makes it into an array until 0 is entered.
// It then computes the maximum #, amount of negative #s and the sum of the positive #s.
import java.util.*;
import java.text.*;;

public class Assignment9 {

//main method initializes variables then calls method assignment9
public static void main(String[] args)
{
    int count = 0;
    ArrayList<Double> help = new ArrayList<Double>();
    assignment9(help, count);
}//end main

//adds user input to array until 0 is entered; it then calls other methods
public static void assignment9(ArrayList<Double> help, int count)
{
    DecimalFormat fmt = new DecimalFormat("#.##");
    double input;
    double max = 0;
    int negative = 0;
    double sum = 0;
    Scanner scan = new Scanner(System.in);

    input = scan.nextInt();

    if (input == 0)
    {
        double[] numbers = new double[help.size()];
        for(int i = 0; i < numbers.length; i++)
        {
            numbers[i] = help.get(i);
        }
        findMax(numbers, count, max);
        countNegative(numbers, count, negative);
        computeSumPositive(numbers, count, sum);
        System.out.println("The maximum numer is " + fmt.format(max));
        System.out.println("The total number of negative numbers is " + negative);
        System.out.println("The sum of positive numbers is " + fmt.format(sum));
        System.exit(0);
    }else{
            help.add(input);
            count++;
            assignment9(help, count);
    }//end if
}//end assignment9

//compares elements of array to find the max until count = -1
public static double findMax(double[] numbers, int count, double max)
{

    if (count == -1)
    {
        return max;
    }else if(numbers[count] > max){
        max = numbers[count];
        count--;
        findMax(numbers, count, max);
    }//end if
    return max;

}//end findMax

public static int countNegative(double[] numbers, int count, int negative)
{

    if(count == -1)
    {
        return negative;
    }else if(numbers[count] < 0){
        negative++;
        count--;
        countNegative(numbers, count, negative);
    }
    return negative;
}//end countNegative

public static double computeSumPositive(double[] numbers, int count, double sum)
{
     if(count == -1)
     {
         return sum;
     }else{
         sum = sum + numbers[count];
         count++;
         computeSumPositive(numbers, count, sum);
         return sum;
     }
}//end computeSumPositive

}//类(class)结束

最佳答案

问题在于,您将数字 count 传递到 findMax 中,并且在尝试访问上限时抛出 ArrayIndexOutOfBoundsException这一行:

} else if (numbers[count] > max) {

请记住,Java 中的数组是从零开始的。另外,由于 Java 使用按值传递,您需要将结果分配给 findMax 的输出:

max = findMax(numbers, count - 1, 0);
<小时/>

逻辑上,findMax 将始终返回最后数字,而不是最大数字。您需要从递归方法中返回临时 max:

double findMax(double numbers[], int count, int index) {
   // This needs to be size - 1 because the array is 0-indexed.
   // This is our base case
   if (index == count - 1)
      return numbers[index];

   // Call the function recursively on less of the array
   double result = findMax(numbers, count, index + 1);

   // Return the max of (the first element we are examining, the max of the
   // rest of the array)
   if (numbers[index] > result)
      return numbers[index];
   else
      return result;
}

此版本在内部处理count索引上限:

max = findMax(numbers, count, 0);

关于java - 索引越界异常但无法找出问题所在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15711405/

相关文章:

java - 如何从 Eclipse 将 Maven 项目的 WAR 部署到 JBoss 服务器?

java - 按键连接两个 map

c++ - Leetcode 108.将排序后的数组转换为二进制搜索树

java - 如何在 Spring Data 中按升序对一列进行排序,对另一列进行降序排序?

c++ - 为什么将 unique_ptr 与数组一起使用会导致编译错误?

c# - 随机分配不同面值的纸币以匹配总面值

javascript - 在 O(n) 内获取两个数组之间所有可能的乘法值?

c++ - 分区问题的递归函数

java - 使用 BigIntegers 和 memoization 调用递归方法时获取 NULL

java - 无法验证 pdf 签名。 itext、pdf、GOST3410