So I'm trying to write this in a short way:

char letter; while ( letter!='A' && letter!='B' && letter!= 'C... letter!= 'a' && letter !='b' && letter!=c) 

Basically if the user does not input a letter between A and C, a while loop will run until A,B,C,a,b,c is inputted.

It should be in the form of

while(letter<'a' && letter > 'c')

but it didn't work apparently because if I inputted F, is it greater than 'C', but it is less than 'c', since char uses ACSII.

2

5 Answers

There are many ways to do this check.

char letter; while (!(letter >= 'A' && letter <= 'C') && !(letter >= 'a' && letter <= 'c')) 

Or you can use Character.toUpperCase or toLowerCase on the letter first, to remove half of the conditions.

Or, if the range of letters is small or non-contiguous, you could do:

char letter; while ("ABCabc".indexOf(letter) == -1) 

There are more ways of course.

2

Set letter to lower case and then check:

letter = Character.toLowerCase(letter); while (letter < 'a' && letter > 'c') { // ... } 

This way, even if the user enters an upper case letter, the check will work.

You need two conditions and a bit of de Morgan:

while(!((letter >= 'A' && letter <= 'C') || (letter >= 'a' && letter <= 'c'))) 

or good old regex

 char input = 'B'; Pattern p = Pattern.compile("a|b|c", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher("" + input); if (m.find()) { System.out.println("found"); } 

You can check with ASCII code of characters such as 65 for 'A' and 97 for 'a'. So you could do if (letter > 65) to check if letter greater than 'A'. Hope this helps. Updates : For checking if letter is only either of A,B,C,a,b,c, use this check : if (letter >= 65 && letter <= 67) || (letter >= 97 && letter <= 99) . Please mark as answer if this helps.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy