Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Counter not working properly

counter stack

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1 pcSetUp

pcSetUp

    CC Regular

  • Member
  • PipPipPip
  • 44 posts

Posted 02 April 2013 - 12:27 PM

Code is attached!

I may just be simply making a mistake but it seems like my counter isnt working?

 public static void main(String[] args) {

        Stack<Character> stack = new Stack<Character>();
        String input;
        int count = 0;
        boolean test = true;

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter a string");
        input = keyboard.nextLine();



        for (int i = 0; i < input.length(); i++) {
            if (input.charAt(i) == '(') {
                stack.push('(');
                count++;
            } else if (input.charAt(i) == ')') {
                if (!stack.empty()) {
                    stack.pop();
                    count--;
                } else {
                    System.out.println("Stack is empty");
                }


            }

        }
        if (!stack.empty()) {
            System.out.println("Stack is not well formed");

        } else {
            System.out.println("Stack is well formed");

        }
        System.out.println(count);
        if (count == 0) {
            System.out.println("There is an equal number of parenthesis!");
        } else {
            if (count > 0) {
                System.out.println("There are too many left parenthesis");
                test = false;
            } else {
                System.out.println("There are too many right parenthesis");
                test = false;
            }
        }

    }
}

 

 



#2 Roman Y

Roman Y

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 196 posts

Posted 02 April 2013 - 12:49 PM

I don't think it's the counter. If you have more closing parentheses than opening parentheses your stack will not go below zero and that will give you an incorrect answer, saying that the parentheses are evenly matched.

 

this change should fix the problem:

 

} else {
    System.out.println("Stack is empty");
    count--;
    break;
}


EDIT:

Although the System.out.println(count) will be incorrect since it will jump out of the loop when it discovers that you have too many closing parentheses.


Edited by Roman Y, 02 April 2013 - 12:53 PM.





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download