0
import java.util.Scanner;
public class testFixedCapacityStack {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        FixedCapacityStack<String> s;
        s = new FixedCapacityStack<String>(100);

       while(sc.hasNext()) {

           String item = sc.next();
           if(!item.equals("-")) {
               s.push(item);
           } else if (!s.isEmpty()) {
               System.out.print(s.pop() + " ");
           }
       }
        System.out.println(s.size());
    }

}

I have no idea why the last line is not getting executed. Someone please point out where I did wrong. Thank you.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

1 Answers1

0

Your code is requesting a new string as input and continuing the loop if it's not empty. This is making your while loop a never-ending loop. That is the reason the last line is not executing. You can insert an if-statement in the loop for an exit string.

import java.util.Scanner;
public class testFixedCapacityStack {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        FixedCapacityStack<String> s;
        s = new FixedCapacityStack<String>(100);

       while(sc.hasNext()) {

           String item = sc.next();
           if(item.equals("/")) {
               break;
           }
           if(!item.equals("-")) {
               s.push(item);
           } else if (!s.isEmpty()) {
               System.out.print(s.pop() + " ");
           }
       }
        System.out.println(s.size());
    }

}

Now when you enter the value "/" as the input, it will get out of the while loop and the last line will execute.

Simran Sharma
  • 852
  • 7
  • 16