That is not a crash, that's an infinite loop. The program becomes unresponsive because you are probably executing this code inside an ActionListener
attached to the JTextField
or a JButton
which is called by the EDT thread.
A GUI java application is not like a console application, there are multiple threads involved and you should not block the event thread with a loop like in your example. You have some unused code:
char input = scan.next().charAt(0);
which was blocking in your console version for input. Now you don't need a loop anymore because it's the user itself which will repeat the action on the user interface and call the actionPerformed
method multiple times.
What do you want to do exactly? Verifying that the entered text is a permutation of the hidden word? Or just check the first character? In both situations you should remove the loop and store your variables outside the actionPerformed
method:
int wrongCounter = 0;
int rightCounter = 0;
public void actionPerformed(ActionEvent e) {
char currentCharacter = textField.getText().charAt(0);
if (set.contains(currentCharacter)) {
++rightCounter;
// whatever
}
else {
++wrongCounter;
}
if (set.size() == 0 || wrongCounter == 8)
hangMan(); // doesn't need parameter anymore, it's outside the method
}