Can I use a range of values ​​on a single switch?

I'm trying to simplify the Card class, and I'm wondering if there is a way to use a range of values ​​in a switch statement?

CONSIDER:

if((card<14)) suit="Hearts"; else if((card>14)&&(card<27)) suit="Clubs"; etc. 

Instead, I would like to use a switch statement, for example:

 switch(card){ case1: through case13: suit="Hearts"; break; etc. 

I could not find anything in the Java tutorials that suggest that such a variation of the switch exists. But is there?

+4
source share
5 answers

The best thing you can do is something like this (see below). Therefore, in some cases (no pun intended :)), it is better to use the if statement.

 switch(card){ case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: suit="Hearts"; break; } 

However, another approach that you might consider is to use a map.

 Map<Integer, String> map = new HashMap<Integer, String>(); for (int i = 1; i <= 14; ++i) { map.put(i, "Hearts"); } for (int i = 15; i <= 26; ++i) { map.put(i, "Clubs"); } 

Then you can search for a card suit with a card.

 String suit1 = map.get(12); // suit1 will be Hearts after the assignment String suit2 = map.get(23); // suit2 will be Clubs after the assignment 
+8
source

Java does not allow you to do such things, unfortunately. Other JVM languages ​​may, however, be Scala .

+3
source

This was suggested in Project Coin some time ago.

Basically, the switch operator now works with built-in and objects. Although there is a certain range for choosing two built-in modules, switches that work with objects do not have a clearly defined range. Currently, two classes of objects are supported, Strings and Enum .

Is the "car" between "A" and "D"? Depends on how you like to handle case sensitivity.

Is MyEnum.ONE to MyEnum.TWO ? Depending on this, in production code this is a very bad idea (as Josh Bloch would like to explain), and if you need an order, the supported way is to implement an unindexed linked comparator. This much better practice will be difficult to integrate into a simple switch, without forcing each enumeration to perform ordering (which does not make sense for enumerations that are not ordered).

A proposal for a project coin is found here .

Josh Bloch: A great presentation on why not rely on implicit ordering of listings is here in the presentation .

+1
source

This is the best you get:

 switch(card){ case1: case2: case3: suit="Hearts"; break; 
0
source

Some libraries provide the "Range" function. It will not work with the syntax of the switch, but it must do the job.

For example, the Range Guava class.

 Range hearts = Ranges.closed(1, 13); Range clubs = Ranges.closed(14, 17); // ... if (hearts.contains(value)) { // case heart... } else if (clubs.contains(value) { // case club... } // ... 
0
source

Source: https://habr.com/ru/post/1402969/


All Articles