Android:寻找使用带变量的开关的等价物

时间:2017-08-25 10:06:23

标签: java android switch-statement

在我的应用程序中,我需要按一下按钮播放声音(骰子滚动声音更具体)但我不想播放与前一个相同的声音,因为掷骰子从不发出相同的声音

所以,我有4种不同的声音,如果可能的话,我想选择相同的概率,其中一种还没有播放

要做到这一点,我想用这个:

MediaPlayer sound1, sound2, sound3, sound4;
Random rnd;

//Random and MediaPlayer are set up in the onCreate method

public void playSound() {
    int a, b, c, d, pos = 0, neg = 0;

    if (sound1.isPlaying()) {neg++; a = neg;} else {pos++; a = pos;}
    if (sound2.isPlaying()) {neg++; b = neg;} else {pos++; b = pos;}
    if (sound3.isPlaying()) {neg++; c = neg;} else {pos++; c = pos;}
    if (sound4.isPlaying()) {neg++; d = neg;} else {pos++; d = pos;}
    //available MediaPlayer associated to 1, 2, 3 ...
    //other MediaPlayer associated to -1, -2, -3 ...

    if (pos>0){
        switch (rnd.nextInt(pos) + 1) {
            case a: sound1.start(); break;
            case b: sound2.start(); break;
            case c: sound3.start(); break;
            case d: sound4.start(); break;
        }
    }
    //pick a MediaPlayer among those associated to a positive number
}

但Android不允许在大小写中使用变量,因此我收到错误消息“需要使用常量表达式”

问题是:如何通过使用android允许使用的东西来做同样的事情?

作为初学者,我没有找到任何答案,除了使用列出所有可能案例的“if”

(我对一个巨大的“if”并不感兴趣,因为我计划添加2或3个其他声音,可能性的数量将达到2 ^ 6或2 ^ 7,意味着64或128)

提前谢谢

1 个答案:

答案 0 :(得分:1)

如果您允许将声音放入阵列中(当您想要添加更多声音时,这是一种更好的方法),您可以更轻松地完成所有这些操作。

在纯Java中(在这里使用8):

MediaPlayer sounds[] = {sound1, sound2, sound3, sound4};
Random rnd;

public void playSound() {
    // Collect candidates - i.e. those that aren't playing right now.
    List<MediaPlayer> candidates = Arrays.stream(sounds)
            // Only not-playing ones.
            .filter(s -> !s.isPlaying())
            .collect(Collectors.toList());
    // Pick a random one.
    MediaPlayer picked = candidates.get(rnd.nextInt(candidates.size()));
    // Play your sound.

}

候选人聚会的Java-7版本

    // Collect candidates - i.e. those that aren't playing right now.
    List<MediaPlayer> candidates = new ArrayList<>();
    for ( int i = 0; i < sounds.length; i++) {
        if ( !sounds[i].isPlaying() ) {
            candidates.add(sounds[i]);
        }
    }