【问题标题】:Android - How to simplify multiple of ten?Android - 如何简化十的倍数?
【发布时间】:2018-11-24 02:57:08
【问题描述】:

我想要多个这样的值:

if (currentScore == 10 | currentScore == 20 | currentScore == 30 | currentScore == 40 | currentScore == 50 | currentScore == 60
            | currentScore == 70 | currentScore == 80 | currentScore == 90 | currentScore == 100 | currentScore == 110
            | currentScore == 120 | currentScore == 130 | currentScore == 140 | currentScore == 150 | currentScore == 160
            | currentScore == 170 | currentScore == 180 | currentScore == 190 | currentScore == 200) {
        editor.putInt("TOP_LEVEL", topLevel + 1);
        editor.apply();
    }

如何简化该代码以便计算许多 currentScore。 谢谢

【问题讨论】:

    标签: java android multiplication


    【解决方案1】:

    使用Java %operator

    if (currentScore % 10 == 0) {
        editor.putInt("TOP_LEVEL", topLevel + 1);
        editor.apply();
    }
    

    % 运算符返回一个余数。如果“currentScore”除以 10 的余数是 0,这意味着 currentScore 是 10 的整数倍。

    【讨论】:

      【解决方案2】:
      int j = 10;
      
      for (int i = 1; i <= 20 ; i++) {
           if (currentScore == j) {
               editor.putInt("TOP_LEVEL", topLevel + 1);
               editor.apply();
               break;
           }
           j = j + 10;
      }
      

      【讨论】:

      • 这不适用于除 currentScore 为 10 以外的任何其他数字,例如如果 currentScore = 100,您的程序将无法运行。即便如此,你为什么还要打印 20 次?
      • 我编辑了我的答案,现在可以正常工作了 :) 谢谢@vshcherbinin
      猜你喜欢
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 2011-12-08
      • 2011-07-14
      • 1970-01-01
      相关资源
      最近更新 更多