DJOwen
DJOwen

Reputation: 21

String.contains always appears false

public final void nameErrorLoop () {
    while (error) {
        System.out.println("Enter the employee's name.");
        setName(kb.next()); 
        if (name.contains("[A-Za-z]")) {
            error = false; 
        }
        else {
            System.out.println("The name can only contain letters.");
        }
    }
    error = true; 
}

Despite a similar setup working in a different method, this method becomes stuck in a constant loop because the if statement is always false. I've tried .matches(), and nothing that I found on the Interent has helped so far. Any ideas why? Thanks for your help in advance.

Edit: I just noticed as I was finishing the project, that trying to print 'name' later only shows the first name, and the last is never printed. Is there any way I can get the 'name' string to include both?

Upvotes: 0

Views: 1264

Answers (2)

ldmtwo
ldmtwo

Reputation: 475

Easy. .contains() is not what you think. It does exact String matching.

    "anything".contains("something that's not a regular expression");

Either use this

Pattern p2=Pattern.compile("[A-Za-z]+");//call only once
p2.matcher(txt).find();//call in loop

or this:

    for(char ch: "something".toCharArray()){
        if(Character.isAlphabetic(ch)){

    }
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503449

String.contains doesn't use regular expressions - it just checks whether one string contains another, in the way that "foobar" contains "oob".

It sounds like you want to check that name only contains letters, in which case you should be checking something like:

if (name.matches("^[A-Za-z]+$"))

The + (instead of *) will check that it's non-empty; the ^ and $ will check that there's nothing other than the letters.

If you expect it to be a full name, however, you may well want to allow spaces, hyphens and apostrophes:

if (name.matches("^[-' A-Za-z]+$"))

Also consider accented characters - and punctuation from other languages.

Upvotes: 11

Related Questions