Search code examples
javaarrayscountcomparecharat

Java:compare an input to a char Array using charAt


I would like to compare String input to the char[] List.If a letter inside the string is equal to the char[] List, the count should iterate but it always prints out 0. Thanks!

    char[] List={'a','b','c','d'};

    int count=0;
    for(int i=1;i<List.length-1;i++){
        if(input.charAt(i)==List[i]){
            count++;
        }
    }
    System.out.println(count);

Solution

  • You are skipping the first and last characters of the List array, and beside that, you only compare the i'th input character to the i'th character in your List array. You need a nested loop in order to compare all the characters of the input String to all the characters of the List array.

    char[] List={'a','b','c','d'};
    
    int count=0;
    for(int i=0;i<List.length;i++){
        for (int j=0;j<input.length();j++) {
            if(input.charAt(j)==List[i]){
                count++;
            }
        }
    }
    System.out.println(count);