我试图编写一个将字符串拆分为ArrayList的程序,但我一直在获取java.lang.StringIndexOutOfBoundsException: String index out of range: <length of string>。有人有什么想法吗?(我已经导入了ArrayList和List类)
public static void main(String[] args)
{
String test = "Hello, World!";
int testLength = test.length();
List<Character> testChars = new ArrayList<Character>();
for(int i = 1; i <= testLength; i++){
testChars.add(test.charAt(i)
}
System.out.println(testChars);
}发布于 2014-11-21 18:00:14
当i到达testLength时会发生异常,因为索引从零开始,以字符串减去1的长度结束。
变化
for(int i = 1; i <= testLength; i++){至
for(int i = 0; i < testLength; i++){发布于 2014-11-21 18:00:36
字符串字符的索引从0到test.length()-1。
因此,循环应该是:
for(int i = 0; i < testLength; i++){发布于 2014-11-21 18:02:39
两个答案都是正确的。请记住,Java中的数组(以及字符串)都是零索引的,所以您应该从0开始,否则就会丢失第一个元素。当数组从0开始时,应该是testLength - 1。
如果testLength是10,那么.9是10,所以应该循环0到9。
for(int i = 0; i <= testLength -1; i++)https://stackoverflow.com/questions/27067498
复制相似问题