调用函数的按钮导致被调用函数的参数变为空?

时间:2018-11-04 21:54:16

标签: java user-interface

在创建用于搜索输入文件的函数中,我很难确定我认为是某种逻辑错误。

该函数采用字符串,然后在第一次运行时像平常一样搜索文件。此后,该值将变为空白(无需任何代码),并且搜索未找到匹配项。这是有问题的函数:

public String searchByName(String str) {
    String value = str.trim().replace(" ", "");
    String st = "\nResults:\n";

    for (SeaPort port:ports) {
        if (port.name.equalsIgnoreCase(value)) {
            st += "\nPort: " + port.name + " " + port.index;
        }
        ArrayList<Dock> docks = port.getDocks();
        for (Dock dock:docks) {
            if (dock.name.equalsIgnoreCase(value)) {
                st += dock.toString();
            }
        }
        ArrayList<Person> persons = port.getPersons();
        for (Person person:persons) {
            if (person.name.equalsIgnoreCase(value)) {
                st += person.toString();
            }
        }
        ArrayList<Ship> ships = port.getShips();
        for (Ship ship:ships) {
            if (ship.name.equalsIgnoreCase(value)) {
                st += ship.toString();
            }
        }
    }

    return st;

}

此外,这是调用上述内容的按钮上的操作侦听器后面的功能:

public void searchFile() {
    if (file == null) {
        textArea.append("\nCannot search. Please select a file first.");
    } else {
        world = new World(sc);

        String term = textField.getText();
        String selection = (String) searchOptions.getSelectedItem();

        switch (selection) {
        case "Index":
            int i;
            try {
                i = Integer.parseInt(term);
                textArea.append("\nSearching for " + i + " by " + selection + "\n\n");
                textArea.append(world.searchByIndex(i));

            } catch (NumberFormatException e) {
                textArea.append("\nError with input. Number required to search ID");
            }
            break;
        case "Type":
            textArea.append("\nSearching for " + term + " by " + selection + "\n\n");
            textArea.append(world.searchByType(term));
            break;
        case "Name":
            textArea.append("\nSearching for " + term + " by " + selection + "\n\n");
            textArea.append(world.searchByName(term));
            System.out.println(term);
            break;
        default:
            break;
        }
    }
}

我觉得奇怪的是,我的测试打印语句继续保留该字符串,但不打印结果。这是连续按两次“搜索”后的屏幕截图: enter image description here

我无法想到可能导致此问题的原因。最初,在开发这三种方法时,我以为switch语句是导致错误的原因,因此在进一步进行故障排除之前,我等待构建此方法。但是,这段代码是如此中断。问题可能是港口中只有一个SeaPort吗?

0 个答案:

没有答案