这是我关于堆栈溢出的第一个问题,但我有一些 Java 经验。我现在正在制作一个 Java 应用程序(575 行并且还在计数!)并试图在 ArrayList 中搜索一个字符串。但我不希望它是准确的!让我澄清一下:我想遍历每个 ArrayList 元素并在该字符串中搜索另一个字符串。如果在 ArrayList 元素中找到该字符串,(现在)我希望它打印到控制台。我希望我已经足够清楚了。
以下是相关代码。定义了所有变量并编译了代码,只是不打印输出(来自搜索功能)。我很确定这是因为 for 循环没有执行,但我很困惑为什么。
//the keylistener that calls the search() function, attached to a JTextField that the query is entered into
class searchFieldListener implements KeyListener {
searchFieldListener() {
}
public void keyTyped(KeyEvent event) {
if (event.getID() == KeyEvent.KEY_TYPED) {
query = searchField.getText()+Character.toString(event.getKeyChar());
System.out.println(query);
for (i = 0; i == nameList.size(); i++) {
search(query, i);
}
}
}
public void keyReleased(KeyEvent event) {
}
public void keyPressed(KeyEvent event) {
}
}
//the troublesome search() function
void search(String query, int iter) {
searchString = nameList.get(iter);
System.out.println(searchString);
if (searchString.indexOf(query) != -1) {
System.out.println(Integer.toString(iter));
} else {
System.out.println("not found \n");
}
}
变量/对象和用途:
- searchFieldListener
JTextField 的 KeyListener 称为 searchField,原因很明显。 - query
要搜索的文本字符串。 - i
为什么每个人都在循环中使用 i?我想这是一种编码传统。 - nameList
名称的 ArrayList(嗯,呃)。 - searchString
要在其中搜索的字符串(如尝试在searchString中查找查询)。 - iter
for 循环到目前为止的迭代次数。
再一次,我希望我已经足够清楚了。谢谢!