随笔-10  评论-11  文章-20  trackbacks-0
         在学习java的过程中,不管你是新手还是工作很多年的老鸟,都会遇到一些常见的异常错误。这篇博文就来简单的介绍下数组越界的异常错误,主要是帮助新人认识下这个异常。该异常在编译的时候不会出错,但是在运行的时候才能报错。

大家看如下代码:

public class F3 {
      public static void main(String args[])       
      {
               int[] i={1,2,3,4,5};
   
               for(int j = 0 ; j < 6 ; j++)
              {
                        System.out.println(i[j]);
               }
       }

}

         这是一段想要遍历整个数组所有元素的代码,但是因为种种愿意在for循环中计算错了控制量j的取值范围,编译的时候并不会出现错误,但是在运行的却会报如下错误:



--|
   |------这部分依然正常运行
   |
   |
---  
~~~~~~这里却出现了错误异常






        
        这就是数组越界报出的异常,原因就在于数组i{1,2,3,4,5}一共有五个元素,但是在for循环中却遍历了数组六次,很明显访问越界了,但是就整段代码来讲并没有语法上的错误。那么在遍历数组的时候,为了避免此类错误的发生,建议读者将for循环中 j < 6 替换为 j < i.length 。也就是说尽量让电脑自己计算数组长度,从而避免自己在写代码的过程中出现这些虽小但是却很讨厌的错误。细节决定成败。



正确代码如下:

public class F3 {
      public static void main(String args[])       
      {
               int[] i={1,2,3,4,5};
   
               for(int j = 0 ; j < i.length ; j++)
              {
                        System.out.println(i[j]);
               }
       }

}

运行结果如下:



posted on 2010-10-09 09:54 Soap MacTavish 阅读(32869) 评论(2)  编辑  收藏

评论:
# re: 小议ArrayIndexOutOfBoundsException 数组越界异常 2012-08-13 08:50 | beiyeren
最好改成这样
public class F3 {
public static void main(String args[])
{
int[] i={1,2,3,4,5};

for(int j = 0,k=i.length ; j < k ; j++)
{
System.out.println(i[j]);
}
}

}

  回复  更多评论
  
# re: 小议ArrayIndexOutOfBoundsException 数组越界异常 2013-10-04 15:50 | glove
package winner;
import java.util.Scanner;
public class CountEachNumber {
public static void main(String[] agrs){
Scanner input=new Scanner(System.in);
System.out.print("Enter a string of numbers:");
String s=input.nextLine();
int[] counts = count(s);
for(int i=0;i<counts.length;i++)
System.out.println("There "+((counts[i]==1)?"is":"are")+counts[i]+(char)(i));
}
public static int[] count(String s){
int[] counts=new int[10];
for(int i=0;i<s.length();i++){
if(Character.isDigit(s.charAt(i)))
counts[s.charAt(i)]++;
}
return counts;
}
}
这个出现了Arrayindexoutofbound,求大神解救  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: