我正在尝试编写一个程序,将字符串拆分为 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);
}
最佳答案
当i
达到testLength
时会发生异常,因为索引从零开始并以字符串长度减1结束。
改变
for(int i = 1; i <= testLength; i++){
至
for(int i = 0; i < testLength; i++){
关于java - 列表 <Character> 上的 StringIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27067498/