0

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!

2
  • @Nichowhat you want please specify more inputs and output Commented Feb 6, 2014 at 18:11
  • 1
    Why not use a regex? stackoverflow.com/questions/1437865 Commented Feb 6, 2014 at 18:12

5 Answers 5

3

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]"))

Sign up to request clarification or add additional context in comments.

2 Comments

Would you mind explaining why regex is "elegant" or the better way? compared to while (!input.matches("[qwertQWERT]")
while(!inputs.matches("[qwertQWERT]")) is using the regex. Regex are extremely powerful and in your case, instead of comparing each String separately, you can do it in one line of code. It is also possible to check for more complex conditions using regex such as whether your input starts with a digit etc.
1

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]")

Comments

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

    {

        }

Comments

0

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.

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.