android 有没有办法简化这种嵌套的if-else语句?

6vl6ewon  于 2022-12-21  发布在  Android
关注(0)|答案(2)|浏览(140)

我有一个伪代码,它可以播放不同的音频文件,我读到过一个嵌套的if,时间复杂度是O(m+n),我觉得这还可以,但是如果有一种方法可以简化它,或者降低时间复杂度,那就太好了。

btn_G.onTouchListener(){
  Case Motion.Action_Down:
    if(high_octave){ 

      if(move){ //if the phone is moving
      
        if(sharp){ //if it's a sharp note
        
          if(vibrato){ //if it's vibrato
            Gstream = G.play(loop) //loop a vibrato, sharp, high octave G note

          } else { //if there is no vibrato
            Gstream = G.play(loop) //loop a normal, sharp, high octave G note
          }
          
        } else { //if all are normal notes, no sharps
        
          if(vibrato){ //if there is vibrato
            Gstream = G.play(loop) //loop a vibrato, normal, high octave G note

          } else { //if there is no vibrato
            Gstream = G.play(loop) //loop a normal, high octave G note
          }
          
        }
      } else { //if the phone is not moving
      //if the phone doesn't move, doesn't matter if there is vibrato or not
      
        if(sharp){ //if it's a sharp note
          Gstream = G.play(once) //play a sharp, high octave G note only once

        } else { //if all are normal notes, no sharps
          Gstream = G.play(once) //play a normal, high octave G note only once
        }
        
      }
    } else if(mid_oct){ #middle octave
        //repeat all of that but with middle octave G note

    } else { #low octave
        //repeat all of that but with low octave G note
    }
  Case Motion.Action_Up:
    Gstream = G.stop() // stop the audio
}

这只是一个按钮。我有像8个按钮,我需要这样做。我想使用哈希表,但创建列表,我会检查这样的条件,所以它会是相同的,不是吗?
我也找到了this,但是我这样分离条件不是和嵌套if一样吗?因为我有8个按钮,所以它也会很长很重复吗?
有没有办法缩短它,即使在所有的条件?
抱歉,我是新手。

mepcadol

mepcadol1#

您可以将位掩码用于条件,并将其分组用于switch语句:

int cond1 = 0x1;
int cond2 = 0x2;

switch(cond) {
  case cond1|cond2:
    // both  are true
    break;
  case cond1|0x0:
    // only cond1 true
    break;
  case 0x0|cond2:
    // only cond2 true
    break;
  case 0x0|0x0:
    // both are false
    break;
}
alen0pnh

alen0pnh2#

最后我把它们分成了不同的方法,如下所示:

G_btn.onTouch{
  Case Motion Down:
    if(up){
      horizontal_method(G5, G#5, gStream)
    } else if (down) {
      horizontal_method(G4, G#4, gStream)
    }
  Case Motion Up:
    stop_audio_method(gStream)
}

public void horizontal_method(note, sharp, stream){
  if(horizontal){ //if phone is moving
    loop_num = -1 //looping
  } else { //phone not moving
    loop_num = 0 //play once
  }
  rotate_method(note, sharp, stream, loop_num)
}

public void rotate_method(note, sharp, stream, loop_num){
  if(rotate){ //if sharp
    stream = soundpool.play (sharp, loop_num) //can be looping or not, depends on the loop_num
  } else { //not sharp
    stream = soundpool.play (note, loop_num)
  }
}

public void stop_audio_method(stream){
  stream = soundpool.stop() //stops that specific stream
}

相关问题