java - Counting duplicate strings in array with equals() -
brand new java , cannot seem figure out:
all i'm trying print duplicate string , number of times shows in array (not using hash tables or that, simplistically).
let's array this:
temparray = {"dogs", "cats", "dogs", "dogs", "mice", "snakes", "cats"}
here's code far:
int flowercount = 0; (int j = 0; j < temparray.length - 1; j++) { (int k = j + 1; k < temparray.length; k++) { if( (temparray[j].equals(temparray[k])) && (j != k) ) { system.out.println(temparray[j]); flowercount++; } } }
obviously doesn't work, doing wrong here? seems should simple do, can't nested loops , counter right.
you can sort array using arrays.sort
. put equal elements next each other. can iterate through list while loop, looking consecutive elements equal.
int = 0; while (i < arr.length) { int start = i; while (i < arr.length && arr[i].equals(arr[start])) { ++i; } int count = - start; system.out.println(arr[start] + " " + count); }
Comments
Post a Comment