如何提高切换语句的效率?

时间:2016-09-27 03:33:35

标签: java

我正处于需要为整数增量添加大量案例的场景中。我想知道如何才能让它更高效,更容易阅读? 这是代码:

public static void volumeControl() {
    int selection;
    System.out.println("Volume. 1-10");
    selection = input.nextInt();
    switch (selection) {
        case 1: volume = -10;
            break;
        case 2: volume = -8;
            break;
        case 3: volume = -6;
            break;
        case 4: volume = -4;
            break;
        case 5: volume = -2;
            break;
        case 6: volume = 0;
            break;
        case 7: volume = 2;
            break;
        case 8: volume = 4;
            break;
        case 9: volume = 5;
            break;
        case 10: volume = 6;
            break;
    }

我无法添加它们,因为变量“volume”是一个浮点数!

4 个答案:

答案 0 :(得分:7)

您可以声明并初始化数组作为类的成员,包含音量值,然后只需使用输入的选择作为数组的索引:

"tabsController.formulaPicker({subjectID: $index, withCalc: false})"

答案 1 :(得分:1)

在这种情况下,您可以使用Map。它们主要用于将key映射到values。在这种情况下,您的输入将作为一个整数键,映射到特定的浮点值。

public static void volumeControl() {
    Map<Integer, Float> volume = new HashMap<>();
    volume.put(1, -10f);
    volume.put(2, -8f);
    volume.put(3, -6f);
    volume.put(4, -4f);
    volume.put(5, -2f);
    volume.put(6, 0f);
    volume.put(7, 2f);
    volume.put(8, 4f);
    volume.put(9, 5f);
    volume.put(10, 6f);

    int selection;
    System.out.println("Volume. 1-10");
    selection = input.nextInt();

    System.out.println("volume: " + volume.get(selection));
}

答案 2 :(得分:0)

不是切换,而是通过将输入的数字设置为数组来节省空间,这样就可以一次性保存所有数字。

答案 3 :(得分:0)

只是为了提高rD的答案,

  Map<int, float> volume = new HashMap<>();
    volume.put(1, -10f);
    volume.put(2, -8f);
    volume.put(3, -6f);
    volume.put(4, -4f);
    volume.put(5, -2f);
    volume.put(6, 0f);
    volume.put(7, 2f);
    volume.put(8, 4f);
    volume.put(9, 5f);
    volume.put(10, 6f);


public static void volumeControl(int selected) {
  // Get the volume
  // Notice I did not perform validation checks, if you have to please do it here.
  volume.get(selected);

  // Do whatever you need to set the volume
}

如果可能的话,在其他地方初始化地图,一次又一次地执行该方法会拖累你的表现。

相关问题