java - 在 Java 中从数组中获取时出错

标签 java arrays indexoutofboundsexception

我写了那种代码

int[] count = new int[10];
int i = count.length;
int position = -1;
int num = kb.nextInt();

    while(i > 0)
    {
        if(count[i] == num)
        {
            position = i;
            break;
        }
         i--;
    }

但是我遇到了 java.lang.ArrayIndexOutOfBoundsException 错误

目的是在数组中找到用户选择的数字的最后一次出现。

最佳答案

你设置了i = count.length;。数组在 java 中从 0 开始索引,因此 count[count.length] 超出范围。数组 a 中的最后一个有效索引是 a.length -1

关于java - 在 Java 中从数组中获取时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17342488/

相关文章:

c# - 将项目添加到字典返回 System.IndexOutOfRangeException : Index was outside the bounds of the array

java - 运行 Spring XML 时构建失败

java - Google Calendar API 事件插入

java - Java 8 和 Java 7 中的时区差异

java - java中的日期格式

java - 线程 "main"java.lang.NullPointerException 中的异常 - JAVA 记录数组

PHP - 替换多维数组中的数据,特定键

javascript - 特定对象的 TypeScript 枚举

java - 索引越界 : 1 (java) when passing a string paramater through a method

java - 字符串索引越界异常 : String index out of range: 4