1

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);
4

2 回答 2

2

数组索引从 0 开始到 n-1,所以你的循环应该是:

for(int i=0;i<List.length;i++){
    if(input.charAt(i)==List[i]){//assuming you have same number of characters in input as well as List and you want to compare ith element of input with ith element of List
        count++;
    }
}

如果您需要将输入中的元素与列表中的任何字符进行比较,那么您可以执行以下操作:

 if (input.indexOf(List[i], 0) >= 0) {
     count++;
 }    
于 2015-03-29T10:53:33.817 回答
0

您正在跳过List数组的第一个和最后一个字符,除此之外,您只需将第 i 个输入字符与List数组中的第 i 个字符进行比较。您需要一个嵌套循环,以便将输入字符串的所有字符与List数组的所有字符进行比较。

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);
于 2015-03-29T10:51:04.880 回答