wuno
wuno

Reputation: 9885

java checking string for inputs in a line of code

This is the code I have checking for q

while (!inputs.contains("q"))

How can I add multiple characters in this.. such as q and Q Or if I had like 5 different letters. q w e r t

Thanks!

Upvotes: 0

Views: 71

Answers (5)

yamilmedina
yamilmedina

Reputation: 3395

I'd suggest you to use StringUtils.containsAny from ApacheCommons and using toUpperCase() (or toLowerCase()) method you'll cover both cases:

String input = "Q";
String matcher = "qwert";
while (StringUtils.containsAny(input.toUpperCase(), matcher.toUpperCase().toCharArray()))   
{
    //something
}

Upvotes: 0

David Stanley
David Stanley

Reputation: 343

If all you're looking for single characters you could use a regex character class:

Pattern = Pattern.compile("[qwert]+");
while (!p.matcher(inputs).matches()) {
    ...

You will need to escape any characters that are special characters in regex. And if you need to match more than one character, such as trying to match 'quit' this won't work.

Upvotes: 0

senseiwu
senseiwu

Reputation: 5279

A regex is the elegant way to do it (but you have to learn the basics of it beyond Java). I also love the regex tester in Intellij (probably eclipse also offers similar)

Something like this should help then while(!inputs.matches("[qwertQWERT]"))

Upvotes: 3

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62874

How about this ?

while (!inputs.contains("q") ||  !inputs.contains("Q") || !inputs.contains("e"))
{
    // Code Here.....
}

and so on for the rest of the terminating characters

Or you can use regular expression (and the matches() method):

while (!input.matches("[qwertQWERT]")

Upvotes: 1

Girish
Girish

Reputation: 1717

while (!inputs.contains("q") || 
            !inputs.contains("Q") ||
            !inputs.contains("e") || !inputs.contains("w") || !inputs.contains("r") )

    {

        }

Upvotes: 0

Related Questions