[英]exception occurs while adding array values using “for loop”
I have some code here 我这里有一些代码
String array[]=new String[5];
for(int i=0;i<array.length;i++){
array[i]= "item "+String.valueOf(i);
i++;
}
and this is log message what i got after application crash 这是我在应用程序崩溃后得到的日志消息
java.lang.IndexOutOfBoundsException : Invalid array range: 5 to 5
Could you guys explain me why pls ? 你们能解释一下为什么吗? I just want to declare an array and use for loop to initialize array element, just dont know why my code didn't work .
我只想声明一个数组并使用for循环初始化数组元素,只是不知道为什么我的代码不起作用。 Thank you
谢谢
because key index More increases than index array in your loop . 因为键索引比循环中的索引数组增加更多。
String array[]=new String[5];
for(int i=0;i<array.length;i++){
array[i]= "item "+String.valueOf(i);
}
remove extra i++.. it already redundant except you have some purpose to do so. 删除多余的i ++ ..它已经是多余的,除非您有一些目的。
String array[]=new String[5];
for(int i=0;i<array.length;i++){
array[i]= "item "+String.valueOf(i);
//i++; //remove this.. it already redundant except you have some purpose
}
its java.lang.IndexOutOfBoundsException : Invalid array range: 5 to 5
because of the counter already exceed size of your string which 5 only.. 其
java.lang.IndexOutOfBoundsException : Invalid array range: 5 to 5
因为计数器已经超出了您的字符串大小(仅5)。
use ArrayList
instead 使用
ArrayList
代替
Just do this: 只要这样做:
String array[]=new String[5];
for(int i=0;i<array.length;i++){
array[i]= "item "+String.valueOf(i);
}
That second i++ was causing your index out of bounds. 第二个i ++导致索引超出范围。
Don't increment the 'i' value twice, which is causing this issue. 不要将“ i”值增加两次,这会导致此问题。
String array[]=new String[5];
for(int i=0;i<array.length;i++){
array[i]= "item "+String.valueOf(i);
//i++; //remove this..
}
Instead of using Array[]
you can you Collections
such as ArrayList<String>
or List<String>
. 除了使用
Array[]
还可以使用ArrayList<String>
或List<String>
Collections
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.