phonebook.java项目的搜索功能

phonebook.java项目的搜索功能,java,arrays,search,Java,Arrays,Search,所以我一直在做这个项目PhoneBook.java程序有一段时间了。程序打开一个.txt文件并将其导入按Lastname、Firstname排序的列表中。我正在尝试编写一个搜索函数,它打开一个窗口,要求您输入一个名称,然后单击ok,它将选择搜索的索引。我不明白为什么我下面的searchMI代码不起作用。我很感激你能给我的任何帮助 public class PhoneBook extends Frame implements ActionListener, ItemListener { Menu

所以我一直在做这个项目PhoneBook.java程序有一段时间了。程序打开一个.txt文件并将其导入按Lastname、Firstname排序的列表中。我正在尝试编写一个搜索函数,它打开一个窗口,要求您输入一个名称,然后单击ok,它将选择搜索的索引。我不明白为什么我下面的searchMI代码不起作用。我很感激你能给我的任何帮助

public class PhoneBook extends Frame implements ActionListener, ItemListener {

MenuItem newMI, openMI, saveMI, saveAsMI, exitMI;
MenuItem searchMI, deleteMI, updateMI, newEntryMI, sortMI;
String fileName;
List nameList;
List numberList;
TextField lastName, firstName, phoneNumber;

// implementing ActionListener
public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if(source == newMI) 
    {
        nameList.removeAll();
        numberList.removeAll();
        fileName = null;
        display(-1);
        setTitle("White Pages")
    }
    else if(source == searchMI) 
    {
        String searchName = JOptionPane.showInputDialog(this,
                            "Please enter a name (last first) to search:");
        System.out.println("Name to search: " + searchName);
        int index = nameList.getSelectedIndex();
        String name = lastName.getText().trim() + " " + firstName.getText().trim();
            for(int i=0; i!=index; i++){
                if(nameList.equals(searchName)){
                    nameList.select(index);
                }
                else
                {
                    System.out.println("Error searching for the name: " + searchName);
                }
        ...
建议

  • 为什么会这样:
    int index=nameList.getSelectedIndex()?在这里,所选索引似乎不会为您提供任何有用的信息
  • 这永远不会起作用:
    if(nameList.equals(searchName)){
    。列表不能等于字符串
  • 相反,使用for循环,循环遍历包含字符串的任何集合,我猜是
    名称列表
    ,并将每个项目中包含的字符串与输入的字符串进行比较
  • for循环应该从
    i=0
    i
    (或者
    nameList.size()
    ,如果它是java.util.List)
  • 不要在for循环中使用else块,
    else{System.out.println(“搜索名称时出错:”…
    ),这样做会多次打印else语句
  • 最好使用Swing库组件,而不是AWT
  • 您将希望更好地格式化您发布的代码。每条语句都应该有自己的行。小心和规则的缩进很重要
  • 由于您使用的是GUI中的组件,因此可能不需要JOptionPane。您是否可以从其中一个文本字段中获取搜索字符串

谢谢气垫船,感谢您的回复。很抱歉,这是我第一次发帖。