【问题标题】:if condition inside for loop in javajava中for循环内的if条件
【发布时间】:2015-09-14 16:05:59
【问题描述】:

我将设计一个方法来接收一个包含 n 类 a 的数组列表。此外,它将接收两个变量 start 和 end 。我想为开始和结束变量之间的那些类测试这个条件。例如,如果 start = 5 和 end = 12 。我想检查类 { 5, 6,7,8,9,10,11,12} 是否达到此条件

这是我的代码的一部分

    static void checkDonothing(ArrayList<tt> Result , int condations, int start, int end){

    for(int i = 0; i<Result.size(); i++){

       if (  Result.get(i).number >= start &&  Result.get(i).number <=end){
               //// do action 
                }       
            }
        }

如果所有这些类在结束和开始之间的条件都是真的,我想做这个动作。

你有什么建议吗?

【问题讨论】:

  • 您要检查什么条件? ArrayList 中将包含哪些类? condations 参数是干什么用的?

标签: java if-statement for-loop arraylist


【解决方案1】:

反转您的条件,如果通过,则返回 return。否则执行循环后的动作。

static void checkDonothing(ArrayList<tt> Result , int condations, int start, int end){

    for(int i = 0; i<Result.size(); i++){

        if (!(Result.get(i).number >= start &&  Result.get(i).number <=end)){
           // Note the ! (not) added in the condition to reverse it.
           return;
        }       
    }

    // If it arrives here, your condition has passed for all.
    // So, do the action.
}

【讨论】:

    【解决方案2】:

    如果您使用的是 Java 8,则可以执行以下操作:

    static void checkDonothing(ArrayList<tt> Result , int condations, int start, int end){
        boolean doAction = Result.stream().limit(end).skip(start)
                .allMatch(obj -> obj.equals(condations)/*write your custom condition here*/);
        if(doAction)
        {
            //Do action
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多