user2057220
user2057220

Reputation: 33

Better way to write if statement with a lot of ||

I wonder if there is a more elegant way to write an if statement with a lot of || in java. I've given different values to alphabet letters:

A,O,I,B,T,S,M,N -> 1 
C,D,F,G         -> 5 
W,Y,Z,H,Q       -> 10

So, I want to check a given letter and if is equal with one of the 2nd group for example to get 5. Right now I'm checking like this:

String value;
if (getLetter().equals("Α")|| getLetter().equals("O") ||
    getLetter().equals("I") || getLetter().equals("B") ||
    getLetter().equals("T") || getLetter().equals("S") ||
    getLetter().equals("N") || getLetter().equals("N"))
value = "1";

is there a better way to do it?

Upvotes: 1

Views: 1204

Answers (3)

Alex Salauyou
Alex Salauyou

Reputation: 14338

String letter = getLetter();
if ("AOIBTSMN".contains(letter)) 
    value = "1"; 
else if ("CDFG".contains(letter))
    value = "5";
else if ("WYZHQ".contains(letter))
    value = "10";

Not optimal, but short, clear and self-explaining.

Upvotes: 6

Sashi Kant
Sashi Kant

Reputation: 13455

You can create a HashMap for your purpose.

HashMap<String, Integer> hm = new HashMap<String, Integer>();
hm.put("A",1);
hm.put("B",1);
hm.put("O",1);
hm.put("I",1);
....
hm.put("C",5);
hm.put("D",5);
...

While fetching you don't need an if condition

int value = hm.get("A");  // Will return 1

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499800

Three options:

  • Use a switch statement, assuming you're using Java 7 or 8:

    switch (getLetter()) {
        case "A":
        case "O":
        case "I":
        case "B":
        ...
            value = "1";
        ...
    }
    
  • Use three Set<String> objects

  • (Best, IMO) Use a Map<String, String>

The last option would be something like:

// You'd presumably initialize this in one place...
Map<String, String> map = new HashMap();
map.put("A", "1");
map.put("O", "1");
map.put("I", "1");
...
map.put("C", "5");
map.put("D", "5");
...

String value = map.get(getLetter());

Upvotes: 7

Related Questions