zoukankan      html  css  js  c++  java
  • java.lang.ArrayIndexOutOfBoundsException

    闲着蛋疼,看了下杨辉三角的代码,也自此发现杨辉三角是神一样的东西,如果你看到这篇博客,请你一定百度下杨辉三角

    java代码输出如下

     1 /**
     2  * 
     3  */
     4 package com.yuxi.demo;
     5 
     6 /**
     7  * @ClassName: YanghuiTriangle
     8  * @Description: TODO(这里用一句话描述这个类的作用)
     9  * @author yuxi 
    10  * @date 2015-6-28 上午8:52:52
    11  *
    12  */
    13 public class YanghuiTriangle {
    14     public static void main(String[] args) {
    15         int triangle[][]=new int[12][];// 创建二维数组
    16         // 遍历二维数组的第一层
    17         for (int i = 0; i <= triangle.length; i++) { //这里是产生异常的关键Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
    18                                                     //at com.yuxi.demo.YanghuiTriangle.main(YanghuiTriangle.java:20)
    19 
    20 
    21       //      System.out.println("triangle.length is "+triangle.length);
    22             triangle[i]=new int[i+1];// 初始化第二层数组的大小
    23             // 遍历第二层数组
    24             for(int j=0;j<=i;j++){
    25                 // 将两侧的数组元素赋值为1
    26                 if(i==0||j==0||j==i){
    27                     triangle[i][j]=1;
    28                 }else{// 其他数值通过公式计算
    29                     triangle[i][j]=triangle[i-1][j]+triangle[i-1][j-1];
    30                 }
    31                 System.out.print(triangle[i][j]+"	");         // 输出数组元素
    32             }
    33             System.out.println();               //换行
    34         }
    35     }
    36 }
    View Code

    输出结果如下

     1 1    
     2 1    1    
     3 1    2    1    
     4 1    3    3    1    
     5 1    4    6    4    1    
     6 1    5    10    10    5    1    
     7 1    6    15    20    15    6    1    
     8 1    7    21    35    35    21    7    1    
     9 1    8    28    56    70    56    28    8    1    
    10 1    9    36    84    126    126    84    36    9    1    
    11 1    10    45    120    210    252    210    120    45    10    1    
    12 1    11    55    165    330    462    462    330    165    55    11    1    
    13 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
    14     at com.yuxi.demo.YanghuiTriangle.main(YanghuiTriangle.java:20)
    View Code

    在代码中 for (int i = 0; i <= triangle.length; i++),用了<=符号,就成了这了,原因在于java中,数组下标=数组长度,就警告了

  • 相关阅读:
    Sign in with the app-specific password you generated. If you forgot the app-specific password or need to create a new one, go to appleid.apple.com
    Java Web项目搭建过程记录(struts2)
    微信小程序之菜鸟入门教学(二)
    微信小程序之菜鸟选手入门教学(一)
    html 表单input录入内容校验
    VUE中使用driver.js实现先手引导
    BScroll使用
    VUE使用screenfull实现全屏
    VUE打印功能
    VUE中使用XLSX实现导出excel表格
  • 原文地址:https://www.cnblogs.com/yuxishua/p/4613949.html
Copyright © 2011-2022 走看看