Java Not Greater than Or Equal to Operator for Char Type

29,986

Solution 1

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.

Solution 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.

Share:
29,986
Majestic
Author by

Majestic

Updated on July 09, 2022

Comments

  • Majestic
    Majestic almost 2 years

    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.

  • Scary Wombat
    Scary Wombat over 7 years
    the second way certainly looks more concise
  • S.S.Prabhu
    S.S.Prabhu over 7 years
    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)
  • QBrute
    QBrute over 7 years
    More concise, yes. But I'd still prefer the first version. To me, the intent is much clearer in that one. Especially the way it is parenthesized and the use of the not-operator make it quite fluent to read in my opinion.
  • Tom Blodget
    Tom Blodget over 7 years
    I think what the downvoters are reacting to is that 'A' is much more understandable in the problem domain than 65.