0

I wanted to find a way to do this in java 6, but it doesn't exist:

switch (c) {
  case ['a'..'z']: return "lower case" ;

There was a proposal to add this to the java language some time ago: http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000213.html, has anything materialized in java 7?

What are other ways to rewrite this code in java 6, that would read more like a switch/case:

if (theEnum == MyEnum.A || theEnum == MyEnum.B){
}else if(), else if, else if...

5 Answers 5

2

You could do something like:

switch (c) {
    case 'a':
    case 'b':
    case 'c':
    //...
        doSomething();
        break;
}
Sign up to request clarification or add additional context in comments.

Comments

2

The simplest thing would be:

if (Character.isLowerCase(c)){
    return "lowercase";
}

Which will also work with á ö and the sort

Comments

1

How about this?

if(c>='a' && c<='z')
    return "lower case";

2 Comments

in every language lowercase characters are stored in alphabet order and there are no other characters between them. It belongs to uppercase characters too.
No, it's much more complicated. That is why locale software fails on international markets. E.g. Swedish alphabet is A..Ö with Å, Ä, Ö as separate letters. German alphabet is A..Z. Ä, Ö, Ü are outside of the range but treated as the base letters. Oh, and there is the ß which does not have a capital equivalent. But the code in the question wasn't i18n safe also.
0

To the first part, one options for strings

if(c.equals(c.toLowerCase())) return "lower case";

To the second part, you can use switch with enums....

switch(theEnum){
  case A:
  case B:
     break;
  case C:
     break;
  ...
}

Comments

0

Or:

if (inRange(c, 'a', 'z')) {
    ...
}

or use a regex like normal, or a map, or...

With regards to your enum expression, it depends on what you're actually doing, but it might just be a map with implementations or values.

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.