【问题标题】:Arraylist matching and returning one single boolean resultArraylist 匹配并返回一个布尔结果
【发布时间】:2011-06-19 23:03:58
【问题描述】:

我在将字符串与字符串数组列表匹配并获得单个布尔结果时遇到问题。基本上,我使用 for 循环进行匹配,我得到的只是一系列布尔值。但是我想要的是,当所有布尔值中只有一个时,它将返回一个值,如果是 all ,那么它将返回一个值。代码如下。求助TT

import java.util.*;
public class NewClass {
    public static void main(String [] args){
        ArrayList <String> aList = new ArrayList <String>();
        aList.add("I");
        aList.add("Love");
        aList.add("You");
        aList.add("Black");
        aList.add("Colored");
        aList.add("Ferrari");
        boolean match;
        for(int i = 0; i < aList.size();i++){
            match = aList.get(i).equals("Red");
            System.out.print(match);
        }
        }
    }

【问题讨论】:

    标签: java string arraylist matching


    【解决方案1】:

    包含应该可以解决问题

        if (aList.contains("Red")) {
            //cool
        }
    

    【讨论】:

      【解决方案2】:

      一旦找到匹配项就应该跳出循环,并在循环外打印结果,如下所示:

          boolean match = false ;
          for(int i = 0; i < aList.size();i++){
              match = aList.get(i).equals("Red");
              if(match){
                  break;
              }
          }
          System.out.print(match);
      

      或者,更短的方法是不使用循环,而是调用列表的contains 方法:

          boolean match = aList.contains("Red");
          System.out.println(match);
      

      【讨论】:

        猜你喜欢
        • 2022-12-04
        • 1970-01-01
        • 2013-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-05
        • 2017-07-21
        相关资源
        最近更新 更多