专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Java Exception

java.lang.ArrayIndexOutOfBoundsException异常

发布时间:2010-06-05 12:23:08 文章来源:www.iduyao.cn 采编人员:星星草

刚学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把下面的程序运行一下就明白了。

public class Test {
public static void main(String[] args){
int size = 10;
String[] strings = new String[size];
size=20;
System.out.print(strings.length);
}
}
------解决方法--------------------------------------------------------
楼上的不对!该这样:
public class Test {
public static void main(String[] args){
int size = 10;
int[] ints = new int[size];
for(int i = 0;i <=ints.length;i++)
{
ints[i] = i ;
System.out.println(ints[i]);
}
System.out.print(ints.length);     

友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: