You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免首次点击触发turnAround函数,仅每20次点击执行?

问题解决方法

问题根源在于初始计数nb_shown_lobby为0,首次点击时直接满足0%20==0的判断条件,同时原逻辑的触发时机也错位——本该第20次点击触发turnAround(),实际会在第21次点击时才触发。

只需调整计数递增和条件判断的顺序,先递增计数再判断是否达到20的倍数,即可解决首次触发的问题,同时保证后续每20次点击正常执行:

public void onClick(View v){
    int nb_shown_lobby = sharedpreferences.getInt("nShownLobby", 0);
    // 先递增计数,再判断是否触发turnAround
    nb_shown_lobby += 1;
    if ((nb_shown_lobby % 20) == 0) {
        turnAround();
    }
    editor.putInt("nShownLobby", nb_shown_lobby);
    editor.commit();

    int random = (int) (Math.random() * manyDifferentStrings.length);
    if (random == oldVaue) {
        random = (int) (Math.random() * manyDifferentStrings.length);
    }
    changingText.setText(manyDifferentStrings[random]);
    oldVaue = random;

    try {
        mySound.start();
    } catch (NullPointerException e) {
        mySound = MediaPlayer.create(MainActivity.this, R.raw.sound);
        /* Optional */ // mySound.start();
    }
}

逻辑说明

  • 首次点击:计数从0变为1,1%20≠0,不触发turnAround()
  • 第20次点击:计数变为20,20%20==0,触发turnAround()
  • 后续每20次点击(40、60...)都会触发,完全符合预期

内容的提问来源于stack exchange,提问作者JustMeShortie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 21:06:29