java - 列表 <Character> 上的 StringIndexOutOfBoundsException

标签 java string list exception character

我正在尝试编写一个程序,将字符串拆分为 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/

相关文章:

java - 单元测试和太多模拟

Java 8 将列表拆分为 block 进行处理并在返回结果之前将其合并回来

c# - 使用转义字符/特殊字符/格式计算字符串的长度

c++ - 如何打印有序 C++ 字符串数组的直方图?

javascript - 如何在文本区域中创建列表?

C# For Loop with LIST 使用 LINQ

java - 通过在java中读取mySQL表创建JSON文件

java - 如何检查 char 数组中的至少一个元素是否在字符串中? ( java )

ios - 创建搜索文本字段

java - 编译Java代码时找不到符号