我正在使用这段代码搜索ArrayList
。我使用str.length()
来读取搜索字段值的长度。问题是它在if(movieArrayList.get(i)
部分抛出了“Index out of bounds”异常。我知道它与.substring(0,stringSize)
有关,因为我输入的搜索时间长于ArrayList
中的最短标题。我不确定如何纠正这个问题。
class SearchListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
Object[] movieList = movieArrayList.toArray();
String searchValue = SearchCombo.getSelectedItem().toString();
// System.out.println(searchValue);
if (TelevisionBox.isSelected()) {
switch (searchValue) {
case "Title" : {
// System.out.println(searchValue);
String str = SearchField.getText();
int stringSize = str.length();
for (int i = 0; i < movieArrayList.size(); i++) {
// System.out.println(searchValue);
if (movieArrayList.get(i).getTitle().substring(0, stringSize).equalsIgnoreCase(str)
&& str.substring(0, 2).equals("Te")) {
System.out.println(str);
ResultArea.append(str.toString() + "\n");
}
}
}
}
}
}
}
答案 0 :(得分:2)
您可以使用:
,而不是获取您不确定字符串长度的子字符串String.contains()
//Check if your input string exist in any of your movie names
String.matches()
//Check if your input string matches any of your movie names
String.startsWith()
//Check if any of your movie names begins with the input string
示例:强>
if (movieArrayList.get(i).getTitle().toLowerCase().contains(str))
if (movieArrayList.get(i).getTitle().toLowerCase().matches(str+".*"))
if (movieArrayList.get(i).getTitle().toLowerCase().startsWith(str))
答案 1 :(得分:1)
问题出在这一行:
movieArrayList.get(i).getTitle().substring(0, stringSize)
因为i
的标题可能低于来自stringSize
SearchField.getText()
标题
也可能来自这条线:
str.substring(0, 2)
与以前相同的原因,SearchField.getText().length
可能小于2
。
你可以用Tom建议的startWith方法来解决它。
movieArrayList.get(i).getTitle().toLowerCase().startsWith(str.toLowerCase()) &&
str.toLowerCase().startsWith("te")
请注意,由于startsWith是密钥敏感的,因此必须使用StringLowerCase。