-1
    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 ++;
        }
    }

As you can see I am trying to search for a certain string in a stack.

My stack looks as followed : One, Two, Three, Four, Five.

Method is comparing the values as followed: not found: menuGUI$Node@4ae17538 Three

When using .equals the program is just looped for eternity.

hDDen
  • 145
  • 1
  • 2
  • 13

2 Answers2

0

Add break; after if true and change == to .equals

hDDen
  • 145
  • 1
  • 2
  • 13
0

Follow this code:

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 ++;
    }
}

Notice the differences:

  • All the object types must be compared with the equals() method. This includes the String since it's an object type as well
  • Stop the loop with break, there is no need to go on through the loop since you have found the result.

I suggest you to use a helper variable boolean flagFound and show the text according its value. Do you really want to write out for example 1000 times that target havent been found on 1st, 2nd, 3rd .. 12th ... 176th index?

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.");
}
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • Thank you, Regarding the part that was printing `target haven't been found `, it was only used for myself, for debugging. – hDDen Sep 21 '17 at 13:46