title: Finding index of a stack java
body: <p>Trying to find the index with the last element inputted as 0 using stack, I'm using the method pop(), and peek().</p>
  <p>Here is my code:</p>
  <pre class="lang-java prettyprint-override"><code>public class Main {
      public static void main(String[] args) {
          Stack&lt;String&gt; a = new Stack&lt;&gt;();
  
          a.push(&quot;a&quot;);
          a.push(&quot;b&quot;);
          a.push(&quot;c&quot;);
          a.push(&quot;d&quot;);
          a.push(&quot;e&quot;);
          a.push(&quot;f&quot;);
  
          System.out.println(a);
          String str = &quot;f&quot;;
          int b = 0;
          for (int i = 0; i &lt; a.size(); i++) {
              if (a.peek().equalsIgnoreCase(str)){
                  break;
              }
              a.pop();
              b++;
          }
          System.out.println(str);
          System.out.println(b);
      }
  }
  </code></pre>
  <p>Expected output if str = &quot;f&quot;:</p>
  <pre><code>0
  </code></pre>
  <p>and yes, when I tried using my solution it works properly.</p>
  <p>Until I tried using str = &quot;b&quot;
  Expected output:</p>
  <pre><code>[a, b, c, d, e, f]
  b
  4
  </code></pre>
  <p>Actual output:</p>
  <pre><code>[a, b, c, d, e, f]
  b
  3
  </code></pre>
  <p>Also using str = &quot;a&quot;,
  Expected output:</p>
  <pre><code>[a, b, c, d, e, f]
  a
  5
  </code></pre>
  <p>Actual output:</p>
  <pre><code>[a, b, c, d, e, f]
  a
  3
  </code></pre>
  <p>So for whatever reason until the last two elements on the stack, int b didn't get incremented. Any idea on why this happens?</p>