0

I am creating a number puzzle game in 3 by 3 grid layout panel. First i random 8 numbers and push them to a stack and then pop their value and set them as button text. The application runs fine but sometimes i have this error printed out: Exception in thread "AWT-EventQueue-0" java.util.EmptyStackException at java.util.Stack.peek(Stack.java:102) at java.util.Stack.pop(Stack.java:84)

and it points to this line of code: buttons[i].setText(randomStack.pop() + "");

I know that it is something with the multi-threading but i can not figure out, please help me.

    public Frame() {

        JPanel panel = new JPanel();
        Stack<Integer> randomStack = new Stack();

        while(randomStack.size() < 8) {
            int n = new Random().nextInt(8) + 1;

            if(!randomStack.contains(n)) {
                randomStack.push(n);
            }
        }


        panel.setLayout(new GridLayout(3, 3));
        panel.setPreferredSize(new Dimension(200 ,200));
        buttons = new JButton[9];

        for(int i = 0; i < 9; i++) {
            buttons[i] = new JButton();
            buttons[i].setSize(30, 30);
            panel.add(buttons[i]);

        }

        Random random = new Random();
        int n = random.nextInt(10);
        for(int i = 0; i < 9; i++) {
            if(i != n) {
               buttons[i].setText(randomStack.pop() + "");
            }
        }

        add(panel, BorderLayout.NORTH);

    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Frame().setVisible(true);
        }
    });
}
}

1 Answer 1

2

You put 8 elements and you try to get 9 elements from stack. This is why you get an exception. This has nothing to do with multithreading since your code doesn't start any additional threads. And this code

Random random = new Random();
int n = random.nextInt(10);

might result in n getting value 9 and in this case your for-loop will iterate 9 times

Sign up to request clarification or add additional context in comments.

3 Comments

no i only get 8 elements out. I random a number that i will not pop the stack to that buttons array index.
for(int i = 0; i < 9; i++) this will provide 9 iterations
oh i get it. It may random number 9 and my array's max index is 8 so it will try to pop 9 elements out. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.