I am working with the Stack class in Java and encountered an issue with the search() method. this is my code
package dsa;
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
stack.push("car");
stack.push("van");
stack.push("bike");
stack.push("truck");
System.out.println(stack.search("bike"));
}
}
The search() method returns -1 when I include a leading space before the item I am searching for. Why does this happen?
>Solution :
The stack.search(" bike") is returning -1 because you’re including a space before "bike" in the search query. In the search method, the item you’re searching for must match exactly with the item present in the stack, including any spaces
package dsa;
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
stack.push("car");
stack.push("van");
stack.push("bike");
stack.push("truck");
System.out.println(stack.search("bike"));
}
}