【问题标题】:ArrayIndexOutOfBoundsException: in my array [closed]ArrayIndexOutOfBoundsException:在我的数组中[关闭]
【发布时间】:2013-11-18 10:01:54
【问题描述】:

我有一个以递归方式运行的数组,它会找到数组中的最小数字。我运行程序并在 (Assignment9.java:36) 上收到 ArrayIndexOutOfBoundsException 错误 if (previousMin > numbers[endIndex]) 和 (Assignment9.java:20) double min = findMin(numbers, 0, numbers.length);我知道为什么通常会出现此问题,但我找不到我的代码的修复程序。我不知道我的实际代码是否有效,因为我无法运行该程序。任何建议..

 import java.io.*;
 import java.text.*;


  public class Assignment9

  {

public static void main(String[] args) throws IOException
{


    int [] numbers = new int[100];


    InputStreamReader streamR = new InputStreamReader(System.in);
    BufferedReader inFile = new BufferedReader(streamR);
    String reader = inFile.readLine();

    double min =  findMin(numbers, 0, numbers.length);
    System.out.print ("The minimum number is " + min + ('\n'));

}


public static int findMin (int [] numbers, int startIndex, int endIndex)

     {
         if (startIndex == endIndex)
         {
             return numbers[startIndex];
         }
         else 
         { 

               double previousMin = findMin (numbers, startIndex, endIndex - 1);
               if (previousMin > numbers[endIndex])


             return numbers[endIndex];

         else

         return numbers[endIndex];
         }


}

【问题讨论】:

  • array[array.length],根据定义,对于任何数组,总是抛出 ArrayIndexOutOfBoundsException

标签: java arrays recursion


【解决方案1】:

您正在访问numbers[endIndex],其中endIndex = numbers.length。这在 java 中是不可能的,因为数组索引从 0 开始,最后一个元素位于索引 length-1,因此例外。

【讨论】:

    【解决方案2】:

    numbers.length 将返回数组的长度,从 1 开始。您想在方法调用中使用 numbers.length - 1

    【讨论】:

      【解决方案3】:

      一个包含 100 个元素的数组的编号从 0 到 99。但您在初次调用 findMin 时使用 100 作为 endIndex。因此,当您引用 numbers[endIndex] 时,您已经超出了数组的末尾 - numbers[100] 不存在。

      【讨论】:

        【解决方案4】:

        您应该使用 numbers.length-1 作为结束索引,因为 java 是零索引的,并且 numbers.length 将超出数组的范围。当 startIndex==endIndex 时,返回数值 numbers[startIndex] 将超出范围。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-08-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多