【问题标题】:"java.lang.ArrayIndexOutOfBoundsException: 1" when the size of the array > the index"java.lang.ArrayIndexOutOfBoundsException: 1" 当数组的大小 > 索引时
【发布时间】:2013-08-17 19:44:21
【问题描述】:
public static int[] allBetween()
    {
        Scanner input = new Scanner(System.in);
        int first;
        int last;

        System.out.println("Enter the first number");
        first = input.nextInt();
        System.out.println("Enter the last number");
        last = input.nextInt();

        int[] between = {((last - first) + 1)};

        for(int count = 0; count <= (last - first); count++)
        {
            between[count] = (first + count);
        }

        return between;
    }

我有点生疏,我没有在这里看到问题,我尝试手动将数组的大小分配为 100,并将第一个和最后一个分配给 1 和 5,但它仍然返回相同的错误。

有什么想法吗?

这是我的第一篇关于堆栈溢出的帖子,如果我以不正确的方式发布,请纠正我

【问题讨论】:

  • 您的帖子没有任何问题,但在发布有关运行时错误之前,您可能应该进行更多调试。

标签: java arrays indexing


【解决方案1】:

以下声明:

int[] between = {((last - first) + 1)};

仅使用单个元素初始化数组,其值为 - last - first + 1

改成:

int size = last - first + 1;
int[] between = new int[size];

然后,您可以将循环更改为:

for(int count = 0; count < size; ++count)

【讨论】:

    【解决方案2】:

    问题是:

    int[] between = {((last - first) + 1)}; //initializes array with value
    

    你在这个数组中只有一个值在索引 0 处,如果last-first 大于零,你最终会得到ArrayIndexOutOfBoundsException

    阅读arrays tutorial了解更多信息。

    【讨论】:

      【解决方案3】:

      这一行:

      int[] between = {((last - first) + 1)};
      

      创建一个具有单个元素的数组,其等于((last - first) + 1

      用途:

      int[] between = new int[(last-first)+1];
      

      无论如何,要遍历它,您可以使用更好的可读性/惯用构造:

      for(int count = 0; count < between[length]; count++)
      {
          between[count] = (first + count);
      }
      

      请记住,数组是用括号寻址和标注尺寸的,用大括号显式创建。

      另外,between[count] = (first + count); 看起来很可疑。确保这确实是您想要的,即将betweencountth 元素设置为first+count。那只会使数组充满first, first+1, ...

      【讨论】:

        【解决方案4】:

        你应该替换

        int[] between = {((last - first) + 1)};
        

        int[] between = new int[((last - first) + 1)];
        

        因为您的版本总是创建一个长度为 1 的数组。例如:

        int[] foo = {22};
        

        是长度为 1 的 int[]foo[0]22。而

        int[] bar = new int[33];
        

        创建一个长度为 33 的数组,其中每个索引存储默认值 0

        【讨论】:

          猜你喜欢
          • 2019-03-30
          • 2011-12-13
          • 2023-04-10
          • 2013-11-19
          • 2015-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多