WalidY
WalidY

Reputation: 21

Determine if a JTextField contains an integer

I'm making a word guessing game. The JTextField can't be empty, can't be longer or smaller than 5 and cannot contain numbers. How do I do the last part?

@Override
public void actionPerformed(ActionEvent e) {
    if (text.getText().isEmpty()) {
        showErrorMessage("You have to type something");
    } else if (text.getText().length() != 5) {
        showErrorMessage("Currently only supporting 5-letter words");
    } else if (contains integer){
        showErrorMessage("Words don't contain numbers!");
    } else {
        r.setGuess(text.getText());
    }
}

Upvotes: 0

Views: 2065

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500525

Rather than explicitly checking for numbers, I would suggest whitelisting characters which are allowed. Would letters with accents be allowed, for example? Both upper and lower case? Punctuation?

Once you've worked out your requirements, I suggest you express them as a regular expression - and then check whether the text matches the regular expression.

For example:

private static final Pattern VALID_WORD = Pattern.compile("^[A-Za-z]*$");

...

if (!VALID_WORD.matcher(text.getText()).matches()) {
   // Show some appropriate error message
}

Note that I haven't included length checks in there, as you're already covering those - and it may well be worth doing so in order to give more specific error messages.

You might also want to consider preventing your text box from accepting the invalid characters to start with - just reject the key presses, rather than waiting for a submission event. (You could also change the case consistently at the same time, for example.) As noted in comments, JFormattedTextField is probably a good match - see the tutorial to get started.

Upvotes: 8

DmitryKanunnikoff
DmitryKanunnikoff

Reputation: 2266

if (!text.getText().matches("[a-zA-Z]*")) {
    // something wrong
}

Upvotes: -1

Salah
Salah

Reputation: 8657

create a method that checks if the JTextField has a number like this:

private boolean isContainInt(JTextField field) {

    Pattern pt = Pattern.compile("\\d+");
    Matcher mt = pt.matcher(field.getText());
    return mt.find();
}

Upvotes: 1

Related Questions