Brand new to Java and I cannot seem to figure this out:
All I'm trying to do is print a duplicate string and the number of times it shows up in an array (not using hash tables or anything like that, just very simplistically).
Let's say for an array like this:
tempArray = {"dogs", "cats", "dogs", "dogs", "mice", "snakes", "cats"}
Here's my code thus far:
int flowerCount = 0;
for (int j = 0; j < tempArray.length - 1; j++) {
for (int k = j + 1; k < tempArray.length; k++) {
if( (tempArray[j].equals(tempArray[k])) && (j != k) ) {
System.out.println(tempArray[j]);
flowerCount++;
}
}
}
Obviously this doesn't work, what am I doing wrong here? This seems like it should be so simple to do, but I can't get the nested loops and counter right.
You can sort the array using Arrays.sort
. This will put equal elements next to each other. Then you can simply iterate through the list with a while loop, looking for consecutive elements which are equal.
int i = 0;
while (i < arr.length) {
int start = i;
while (i < arr.length && arr[i].equals(arr[start])) {
++i;
}
int count = i - start;
System.out.println(arr[start] + " " + count);
}