【问题标题】:Java if-statement in for-loopfor循环中的Java if语句
【发布时间】:2021-01-26 17:26:50
【问题描述】:

我的程序中有几个布尔值,当程序运行时,只有一个设置为 true(基于用户在控制台中的输入)。现在我的程序有一个基本的 for 循环,如下所示:for(int i = 0; i < 5; i++){ do this}。但我希望“5”根据哪个布尔值是真的来改变。类似if(boolean1 == true){ i < 5}else if(boolean2 == true){ i < 7}。如何在 java 中实现这一点,而不是为每个布尔值编写不同的 for 循环?

【问题讨论】:

    标签: java for-loop if-statement boolean


    【解决方案1】:

    假设只有两个可能的值 5 或 7,只需执行以下操作:

        int end = boolean1 ? 5 : 7;
        for(int i = 0; i < end; i++){ 
           //do this
        }
    

    为循环条件创建一个变量(例如 end)并相应地设置值。

    如果有更多变量,同样的想法也适用:

        int end = 0;
        if(variable1) end = ... ; // some value 
        else if(variable2) end = ...; // some value
        ...
        else if(variableN) end = ...; // some value  
    
        for(int i = 0; i < end; i++){ 
           //do this
        }
    

    【讨论】:

      【解决方案2】:

      正如 NomadMaker 建议的那样,您可以使用变量作为 for 循环的边界

      boolean bool1;
      boolean bool2;
      int numberOfExecutions;
      
      in your main function
      callTheActionThatSetsOneBooleanToTrue();
      if (bool1) {
          numberOfExecutions = 5;
      }
      if (bool2) {
          numberOfExecutions = 10;
      }
      for (int i=0; i < numberOfExecutions; i++) { doYourThing(); }
      

      【讨论】:

        猜你喜欢
        • 2019-05-04
        • 1970-01-01
        • 1970-01-01
        • 2016-06-16
        • 2019-06-09
        • 1970-01-01
        相关资源
        最近更新 更多