【问题标题】:Checking if a char is included in a list of letters [closed]检查字符是否包含在字母列表中[关闭]
【发布时间】:2020-11-11 12:33:28
【问题描述】:

我是 Java 新手,我想创建一个布尔值来检查 char 是否是列表的一部分,最好的方法是什么? 我尝试过使用枚举,但这似乎不起作用。 有什么帮助吗?

【问题讨论】:

  • java 中的集合(如列表)已经具备此功能。见Collection#contains(Object o)。因此,当您有ArrayList<Character> yourList 时,您可以检查某些字符是否在列表中,例如yourList.contains('A')。此调用将返回一个布尔值,无论该字符是否包含在列表中(true)(false)。

标签: java arrays char


【解决方案1】:

您可以创建一个字符列表。并检查此列表是否包含指定的字符。 请看以下代码:

public static void main(String[] args) {
    List<Character> list = Arrays.asList('H', 'E', 'L', 'L');
    System.out.println(isCharExistInList('c', list));//false
    System.out.println(isCharExistInList('H', list));//true
  }

  private static boolean isCharExistInList(char c, List<Character> list){
    return list.contains(c);
  }

【讨论】:

    【解决方案2】:

    为此,您实际上可以遍历数组并检查要检查的字符是否存在于数组中,您可以这样做:

    public static void main(String[] args) {
            
            //use the wrapper class (Character) and not "char"
            ArrayList<Character> theList = new ArrayList<Character>(); //declare your ArrayList
            
            //insert items to the array list
            theList.add('a');
            theList.add('b');
            theList.add('c');
            theList.add('d');
    
            System.out.println(doesListContain('c', theList)); //call method
        }
    
        public static boolean doesListContain(char c, ArrayList<Character> list) {
            boolean isFound = false; //boolean var to keep track of the availability of character in list
            try {
                for (char character : list) {
                    //iterate over array list using enhanced for loop
                    if(c == character){
                        //if the character is found
                        isFound = true; //set boolean to true
                        break; //stop the loop
                    }
                }
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
            return isFound; //return the boolean variable to the caller
        }
    

    【讨论】:

      猜你喜欢
      • 2012-12-27
      • 2015-01-04
      • 2014-04-22
      • 1970-01-01
      • 2018-04-23
      • 2011-07-11
      • 1970-01-01
      • 2021-06-17
      相关资源
      最近更新 更多