这个异常是Java中的数组越界问题

当你使用不合法的索引访问数组是会出现这种错误
例如:

 class Solution {
public static int climbStairs(int n) {
if (n == 1 || n == 2) {
return n;
}
int[] demo = new int[n];
demo[1]=1;
demo[2]=2;
for (int i = 3; i <=n; i++) {
demo[i] = demo[i-1] + demo[i-2];
}
return demo[n];
}
}
public class palouti {
public static void main(String[] args) {
System.out.println(Solution.climbStairs(3));
}
}

发生这种错误的原因是:

在这个地方开辟数组长度为n

int[] demo = new int[n];  

而在下面的使用中

for (int i = 3; i <=n; i++) {
demo[i] = demo[i-1] + demo[i-2];
}

无论n的值为多少都会超出界限
因为数组的索引是从 0 开始的,前面开辟的长度每次都差了一位
例如:n=3时,在 for 循环的索引中,都会索引到 demo[3],而从 0 开始索引,到demo[3]时,就相当于从 0-1-2-3,超出了数组界限

解决方法也很简单

只要将

int[] demo = new int[n];  

改为

int[] demo = new int[n+1];  

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException:
这个异常会经常遇到,只要注意数组的界限,就可以避免了

最新文章

  1. 解析jquery获取父窗口的元素
  2. Mac下升级Nodejs
  3. 三、jQuery--jQuery基础--jQuery基础课程--第6章 jQuery 事件与应用
  4. csharp: Sound recording
  5. MVC5 + EF6 + Bootstrap3 (14) 分部视图PartialView
  6. jquerymobile使用技巧
  7. psutil--跨平台的进程管理
  8. nyoj 115 城市平乱
  9. GDB反向调试 + 指令记录+函数历史记录
  10. oracle 权限管理
  11. 基于amoeba实现mysql数据库的读写分离/负载均衡
  12. jQuery 基本实现功能模板
  13. Please ensure that adb is correctly located at &#39;...adb.exe&#39; and can be executed.
  14. 第三章 Python 的容器: 列表、元组、字典与集合
  15. iOS textfield 限制输入字数长度
  16. Windows系统下文件的概念及c语言对其的基本操作(丙)
  17. linux zabbix监控服务器搭建
  18. git 三步走
  19. 开车旅行 [NOIP 2012]
  20. pyppeteer使用笔记

热门文章

  1. Python第三周 函数详解
  2. host-manager does not exist or is not a readable directory
  3. 【手把手教程】uniapp + vue 从0搭建仿微信App聊天应用:腾讯云TXIM即时通讯的最佳实践
  4. mybatis注解版in查询、字符串判空模糊匹配 、批量插入、插入返回主键
  5. c++设计模式概述之外观
  6. 【LeetCode】1403. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order
  7. 【九度OJ】题目1174:查找第K小数 解题报告
  8. 【LeetCode】572. 另一个树的子树 Subtree of Another Tree(Python & Java)
  9. 【LeetCode】382. Linked List Random Node 解题报告(Python & C++)
  10. spoj-SUBSUMS - Subset Sums