2016-04-27 156 views
1

我正在使用这段代码来搜索ArrayList。我使用str.length()来读取搜索字段值的长度。问题在于它会在if(movieArrayList.get(i)部分抛出“索引超出范围”异常。我知道它与.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"); 
         } 
        } 
       } 
      } 
     } 
    } 
} 
+3

* “我不知道如何解决此问题” *如何不切割String和使用'startsWith'? – Tom

+0

应该是大小 - 1 – localplutonium

回答

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") 

请注意,您必须对字符串进行LowCase处理,因为startsWith对键敏感。

+0

谢谢你们完美的工作 – ForswornDragon

+0

@ForswornDragon np,请不要忘记接受答案。 – raven

+0

现在好了,那已经整理出来了,我在搜索栏显示结果时遇到了困难。我删除了System.out.println(str);因为这是为了调试目的。我不知道插入ResultArea.append的内容,我知道如果我把movieArrayList放在ArrayList中的所有内容。如果我需要问这是另一个问题,请告诉我。 – ForswornDragon

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))