1

I used to check int values in case statements but is there any way check double values too? I can't use If else. This is an assignment. Thank you.

  • 1
    http://stackoverflow.com/questions/5141830/switch-expression-cant-be-float-double-or-boolean – elaid Feb 18 '15 at 16:12

3 Answers3

0

yes, but it won't perform very well. This will work

// don't do this, unless you want readability not performance.
switch(Double.toString(d)) {
   case "1.0":
        break;
   case "Infinity":
        break;
}

Instead you should use a series of if/else statements or use a Map<Double, DoubleConsumer> for a long list of doubles.

You can use a NavigableMap for efficient range searches.

NavigableMap<Double, DoubleConsumer> map = new TreeMap<>();
// default value is an assertion error
map.put(Double.NEGATIVE_INFINITY, d -> new AssertionError(d));
double upperBound = 12345;
map.put(upperBound, d -> new AssertionError(d));

// if >= 1.0 then println
map.put(1.0, System.out::println);


public static void select(NavigableMap<Double, DoubleConsumer> map, double d) {
    Map.Entry<Double, DoubleConsumer> entry = map.floorEntry(d);
    entry.getValue().accept(d);
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Actually I have an assignment to do this.. Thank you. –  Feb 18 '15 at 16:17
  • @user126494 in which case, readability may be more important than performance. Note: with double you are likely to need rounding or range searches. You can implement range searches with a `NavigableMap` – Peter Lawrey Feb 18 '15 at 16:19
  • Can you please explain NavigableMap with an example.. I'm really new to that. –  Feb 18 '15 at 16:34
0

Switch cases only take byte, short, char, and int. And a few other special cases. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Sdyess
  • 340
  • 1
  • 8
0

Since double values provide an exact representation only in case when the value can be expressed as a sum of powers of 2 that located "close enough" to each other (within the length of mantissa), and because switch works only with exact matches, you cannot use doubles in a switch in a general case.

The basic reason for it is the same as the need to be careful when using == to compare doubles. The solution is the same as well: you should use a chain of if-then-else statements to find the desired value

if (a <= 0.2) {
    ...
} else if (a < 0.5) {
    ...
} else if (a < 0.9) {
    ...
} else {
    ...
}

or use a TreeMap<Double,Something> and perform a limit search:

TreeMap<Double,Integer> limits = new TreeMap<Double,Integer>();
limits.put(0.2, 1);
limits.put(0.5, 2);
limits.put(0.9, 3);
...
Map.Entry<Double,Integer> e = limits.ceilingEntry(a);
if (e != null) {
    switch(e.getValue()) {
        case 1: ... break;
        case 2: ... break;
        case 3: ... break;
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523