将节点与java中的字符串进行比较

时间:2017-09-21 13:03:45

标签: java user-interface search netbeans nodes

    String target = JOptionPane.showInputDialog("Please enter the string you are looking for");
    Node current = top;
    int counter = 0;

    while (current != null) {
        if (current.getElement() == (target)) {
            printTextField.setText(target + " was found, its position is: "+ counter);
        } else {
            System.out.println("not found: "+current +" "+target);
    current = current.getNext();
            counter ++;
        }
    }

正如您所看到的,我正在尝试在堆栈中搜索某个字符串。

我的堆栈如下所示:One, Two, Three, Four, Five.

方法是比较以下值:not found: menuGUI$Node@4ae17538 Three

使用.equals时,程序只是永久循环。

2 个答案:

答案 0 :(得分:0)

break;之后添加if true并将==更改为.equals

答案 1 :(得分:0)

请遵循以下代码:

while (current != null) {
    if (current.getElement().equals(target)) {
        printTextField.setText(target + " was found, its position is: "+ counter);
        break;
    } else {
        System.out.println("not found: "+current +" "+target);
        current = current.getNext();
        counter ++;
    }
}

注意差异:

  • 必须将所有对象类型与equals()方法进行比较。这包括String,因为它也是对象类型
  • 使用break停止循环,因为找到了结果,所以无需继续循环。

我建议您使用辅助变量boolean flagFound并根据其值显示文本。你是否真的想要写出例如1000次,那个目标在第1,第2,第3 ......第12 ......第176指数中找不到?

boolean flagFound = false;

while (current != null) {
    if (current.getElement() == (target)) {
        printTextField.setText(target + " was found, its position is: "+ counter);
        flagFound = true;
        break;
    } 
    current = current.getNext();
    counter ++;
}

if (!flagFound) {
    System.out.println("The target " + target + " haven't been found.");
}