Hello All,
I'm hoping someone can help here. I'm trying to count how many times a string occurs in an array. Here is the code I have ...
String animals[] = {"Cat", "Cat", "Dog", "Dog", "Fish"};
String animalSingle[] = {"Cat", "Dog", "Fish"};
count = 0;
for (int i = 0; i < animalSingle.length; i++)
{
System.out.print(animalSingle);
for (j = 0; j < animals.length; j++)
{
if (animals[j] == animalSingle)
{
System.out.print(" " + j + " ");
}
else
{
}
}
}
This will display the animal and the elements that the animal appears, such as this;
Cat 0 1 Dog 2 3 Fish 4
However, I'm looking for how many times each animal appears in the array. So the output will look like this;
Cat 2 Dog 2 Fish 1
Can someone point me in the right direction? I believe it should just be a matter of counting something but I'm not sure what.
Thanks
I'm hoping someone can help here. I'm trying to count how many times a string occurs in an array. Here is the code I have ...
String animals[] = {"Cat", "Cat", "Dog", "Dog", "Fish"};
String animalSingle[] = {"Cat", "Dog", "Fish"};
count = 0;
for (int i = 0; i < animalSingle.length; i++)
{
System.out.print(animalSingle);
for (j = 0; j < animals.length; j++)
{
if (animals[j] == animalSingle)
{
System.out.print(" " + j + " ");
}
else
{
}
}
}
This will display the animal and the elements that the animal appears, such as this;
Cat 0 1 Dog 2 3 Fish 4
However, I'm looking for how many times each animal appears in the array. So the output will look like this;
Cat 2 Dog 2 Fish 1
Can someone point me in the right direction? I believe it should just be a matter of counting something but I'm not sure what.
Thanks