Java: check if string contains more than one character


I would like to check my inputted string on a comma, which is pretty easy ( just used this: How can I check if a single character appears in a string?). Now I want to check if a character is present more than once. (in this case a comma (/u002C)) I have created this code:

public static void addTextLimiterDouble(final TextField tf, final int maxLength, final Button submitButton) {
    tf.textProperty().addListener(new ChangeListener<String>() {
        public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {

            if (oldValue.contains("\u002C") && newValue.endsWith("\u002C")) {

This gives a StackOverflow error, because it seems it can not get out of the loop. Can anyone explain why it can't?

Note: I know there are maybe more ways to check for more than one character, but I am just curious why this gives me an error.

Any help is greatly appreciated!

5/23/2017 10:25:20 AM

Accepted Answer

Imagine the situation (actually, that's most likely the situation where you are in) where you are editing a string that ends in a comma. When you change something else in that string, then your if statement (if (oldValue.contains("\u002C") && newValue.endsWith("\u002C"))) returns true and you try to revert to the old value by calling tf.setText()

However- that changes the text! And your ChangeListener is invoked again. The new value ends in a comma (you were reverting back to a value that ends in a comma) and the old value also contains a comma, so again, your listener calls tf.setText().

After that, it invokes your ChangeListener because the text was changed. And again... ad nauseum

10/31/2014 11:44:44 AM

You add a Listener to your TextField. Then you override the changed() method. In this method you call setText() !! This will invoke the Listeners' changed() again .... so you end up in an infinite loop ...

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow