2017-06-15 9 views
0

私は全てのインデックス番号を取得する必要があります。キーワード 'Articles'の一致を取得します&また、 'indexoccncencecounter' 。私の上記のコードは私に間違った出力を与えている値を含むすべてのアイテムのインデックスを取得する

List<String> valueslist = new ArrayList<String>(); 
valueslist.add("Articles"); 
valueslist.add("Vals"); 
valueslist.add("Articles"); 
valueslist.add("Toast"); 

String key="Articles"; 

System.out.println("List contents having values are: "+valueslist); 
int ind=0; 
int indexoccurencecounter=0; 
for (int i=0;i<valueslist.size();i++){ 
    ind=valueslist.indexOf(key);  
    if (ind>=0){ 
     indexoccurencecounter++; 
    } 
} 
System.out.println("Index's of the key "+key+" is: "+ind); 
System.out.println("The key specified appears "+indexoccurencecounter+" times in the result links"); 

私は以下のようになり、出力を期待しています、:

List contents having values are: [Articles, Vals, Articles, Toast] 
Index's of the key Articles is: 0,2 
The key specified appears 2 times in the result links 

答えて

2

複数のインデックスが一致するので、int indはそれらすべてを追跡することはできません。それは1つしか追跡できませんでした。インデックスのList<Integer>を作成することをお勧めします。これを行うのに役立つ副作用は、もはや出現回数を数える必要がないということです。—リストのsize()メソッドを使用するだけです。

List<String> values = new ArrayList<>(); 
values.add("Articles"); 
values.add("Vals"); 
values.add("Articles"); 
values.add("Toast"); 

String searchTerm = "Articles"; 

List<Integer> matchingIndices = new ArrayList<>(); 

for (int i = 0; i < values.size(); i++) { 
    String candidate = values.get(i); 
    if (candidate.indexOf(searchTerm) >= 0) { 
     matchingIndices.add(i); 
    } 
} 

int numberOfMatches = matchingIndices.size(); 

System.out.println("Values: " + values); 
System.out.println("Indexes of the key '" + searchTerm + "': " + matchingIndices); 
System.out.println("The key appears " + numberOfMatches + " times."); 

生成します:

Values: [Articles, Vals, Articles, Toast] 
Indexes of the key 'Articles': [0, 2] 
The key appears 2 times. 
+0

パーフェクト!ありがとう... –

関連する問題