【问题标题】:What does ArrayIndexOutOfBoundsException mean and how do I get rid of it? Here is a code sample that triggers the exception: [closed]ArrayIndexOutOfBoundsException 是什么意思,我该如何摆脱它?这是触发异常的代码示例:[关闭]
【发布时间】:2018-06-25 01:39:21
【问题描述】:

我一直在用 java 编写一些代码,但我遇到了一个错误,我不知道为什么,因为我刚刚运行了一些类似这样的代码,它工作得很好。

    String [] month = {"Jan", "Feb", "Mar", "Apr", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

    double [] temperature ={54.3, 57.0, 62.5, 67.6, 74.3, 79.2, 80.9, 80.4, 77.8, 70.1, 62.8, 56.3};    
    double [] precipitation ={3.5, 3.4, 4.3, 2.9, 3.2, 6.8, 6.1, 6.6, 4.4, 2.5, 2.2, 2.6};  
 for( int index = 0; index < temperature.length; index++)
    {
        System.out.print(""+month [index] +".        "+temperature [index]+"         "+precipitation [index]);
        System.out.println();
    }

【问题讨论】:

标签: java arrays indexoutofboundsexception


【解决方案1】:

通过检查,我可以看到您的 month 数组缺少 May 的月份,因此其中只有 11 个元素。结果,当你遍历temperature数组中的12个元素时,你会在最终温度期间得到一个数组越界异常,因为month在那个位置没有对应的enter。

要解决此问题,只需确保 monthtemperature 的大小相同:

String [] month = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
    "Oct", "Nov", "Dec" };

【讨论】:

  • 啊谢谢没听懂。
猜你喜欢
  • 1970-01-01
  • 2013-08-19
  • 2015-02-02
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 1970-01-01
  • 2021-05-30
相关资源
最近更新 更多