java - 修复 ArrayList 中的 IndexOutOfBounds 异常
问题描述
我正在尝试制作一个将所有单词存储在一个句子中的 String ArrayList。目前,我正试图通过查找空间的索引并将其存储在数组中来实现这一点。空格的数组列表有效,但是单词的数组列表无效。字符串数组列表的值是两个空格索引之间的子字符串。请帮忙。
for(int x = 0; x < spaces.size(); x++) {
words.add(post.substring(spaces.get(x) + 1, spaces.get(x + 1)));
}
解决方案
什么时候x
是size()-1
,然后你会调用x+1
which will equal to size()
which is not a valid index
由于您正在查看一个索引,因此仅循环直到小于size()-1
:
for(int x = 0; x < spaces.size()-1; x++) {
words.add(post.substring(spaces.get(x) + 1, spaces.get(x + 1)));
}
推荐阅读
- flutter - 像 instagram 这样的快速闪屏
- elixir - 如何使用 Scenic 将消息从一个场景发送到另一个场景?
- docker - 如何删除多个
docker 镜像被停止的容器快速阻塞 - c - 指向一个空结构
- overflow - 运行时错误:将无符号偏移量添加到 0x602000000390 溢出到 0x60200000038c
- python - 有人可以帮我吗,我尝试运行这个 git 但我遇到了这些错误
- react-native - FlatList 没有渲染它显示除 FlatList 之外的任何内容
- javascript - 如何在展开可折叠 div 时调用 API 并使用 AngularJS 用 API 响应填充其内容?
- laravel - 使用 json_decode 时为 foreach() 提供的参数无效
- c# - 使用带有 Pipedream SSE API 的 ServiceStack ServerEventsClient 时出现 404 未找到错误