当前位置: 代码迷 >> J2SE >> 奇怪的错误。帮小弟我看下,多谢了
  详细解决方案

奇怪的错误。帮小弟我看下,多谢了

热度:12   发布时间:2016-04-24 14:26:39.0
奇怪的异常。帮我看下,谢谢了
刚学JAVA,编了个程序可以编译通过,运行时就出异常了。帮我看下,谢谢了。
//:   c09:E09_StringContainer.java
//+M   java   E09_StringContainer
import   java.util.*;

/******************   Exercise   9   ******************
  *   Create   a   container   that   encapsulates   an   array
  *   of   String,   and   that   only   adds   Strings   and   gets
  *   Strings,   so   that   there   are   no   casting   issues
  *   during   use.   If   the   internal   array   isn 't   big
  *   enough   for   the   next   add,   your   container   should
  *   automatically   resize   it.   In   main(),   compare
  *   the   performance   of   your   container   with   an
  *   ArrayList   holding   Strings.
  ***********************************************/
class   StringContainer   {   //class   container
private   int   size   =   10;
private   String[]   strings   =   new   String[size];
private   int   index   =   0;
public   int     setSize()   {   //if   the   array   isn 't   big   enough,resize  
return   size   =   size*2;
}
public   void   add(String   s)   {//add   string
if(index> =size)   {
setSize();
}
strings[index]   =   s;//||Exception   here||.
index++;
}
public   void   print(){//print   the   list.
for(int   i   =   0;i <strings.length;i++)   {
System.out.println(strings[i].toString());
}
}
public   int   getSize()   {//get   the   size  
return   size;
}
public   int   getIndex()   {//get   the   index   which   record   the  
                                                                //   real   string 's   numbers。
return   index;
}
}
public   class   E09_StringContainer   {
public   static   void   main(String[]   args)   {
StringContainer   strc   =   new   StringContainer();
String[]   strs   =           { "def ", "ghi ", "jkl ", "dadf ", "gfgai ", "gfadio ", "gaodafd ", "fdfdcvsfso ", "fdafdacims ", "fdafi ", "fdifadkm ", "daida ", "idak ", "aok ", "dia ", "fdm "};
for(int   i   =0;i <strs.length;i++)   {
strc.add(strs[i]);//||exception||.
}
strc.print();
System.out.println(strc.getSize());
System.out.println(strc.getIndex());
}
}

异常是这样:
Exception   in   thread   "main "   java.lang.ArrayIndexOutOfBoundsException:   10
at   StringContainer.add(E09_StringContainer.java:26)
at   E09_StringContainer.main(E09_StringContainer.java:46)

------解决方案--------------------
数组索引超范围。LZ把下面的程序运行一下就明白了。
  相关解决方案