【问题标题】:Error java.lang.ArrayIndexOutOfBoundsException [duplicate]错误 java.lang.ArrayIndexOutOfBoundsException [重复]
【发布时间】:2019-03-27 12:02:31
【问题描述】:

我查看了 stackoverflow,但仍然无法弄清楚代码有什么问题。 PS:我是初学者 /************************************************* ***************/

class Main 
{
  public static void main(String[] args) 
  {
    int SIZE = 10;
    int[] sortedArray = new int[SIZE];
    int[] intArray = new int[]{ 5,2,10,4,1,6,99,8,9,1 };
    int x=0;
    int y=0;
    // Random big nunbver to ensure no number in array is bigger
    int biggestNumberFound = 10000000;
    int maxValue=0;
    for ( x = 0; x <= SIZE; x++) 
      for ( y = 0; y <= SIZE; y++)
        maxValue = 0;
        if (intArray[y] > maxValue && intArray[y] < biggestNumberFound)
          maxValue = intArray[y];
      sortedArray[x] = maxValue;
      biggestNumberFound = maxValue;
    System.out.println(sortedArray);
  }

}

/**************************************************** */

错误: 线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:11 在 Main.main(Main.java:17) 退出状态 1

【问题讨论】:

  • 应该是&lt; SIZE
  • 这意味着在 Main.java 的第 17 行中,您访问了一个不存在的索引为 11 的数组元素。
  • 将 x
  • 数组是从零开始的,因此在这种情况下的有效范围是 0 到 9。for 循环从 0 迭代到 10,因此出现错误
  • 另外,你的作用域有问题,在每个 for 循环后添加大括号并指定这个循环应该影响的区域

标签: java arrays exception indexoutofboundsexception


【解决方案1】:
for ( x = 0; x <= SIZE; x++) 

x 应该小于 SIZE 而不是 &lt;=,因为数组以索引 0 开始并以 (size-1) 结束

【讨论】:

  • 我用 x
  • @CatalinPadurean y 也存在完全相同的问题。
  • 也为 y 做过,忘了提
  • @Catalin Padurean 请在块之前添加一些 {} 之后
  • for (x = 0; x &lt;SIZE; x++) { for (y = 0; y &lt; SIZE; y++) { maxValue = 0; if (intArray[y] &gt; maxValue &amp;&amp; intArray[y] &lt; biggestNumberFound) maxValue = intArray[y]; sortedArray[x] = maxValue; biggestNumberFound = maxValue; } }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多