Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does Stack.search() return -1 when searching for an item with leading spaces in Java?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"));
  }  
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading