I currently have a program that works on an array by using a for loop to iterate through the array with an embedded if statement that matches the element in the array to the one I'm looking for. I need to modify this so that it will find the second occurrence of the same element. Ideas on how to do this?
String[] myStringArray = {"a", "b", "c", "a", "d", "e", "f"};
for(int i=0; i<myStringArray.length; i++) {
if(myStringArray[i].equalsIgnoreCase("a") {
//do something
}
}
As noted, this will find the first a and I will do work on it, however the second a needs to be acted upon also.
Use a counter.
String[] myStringArray = {"a","b","c","a","d","e","f"};
int occurrences = 0;
for(int i=0; i<myStringArray.length;i++{
if(myStringArray[i].equalsIgnoreCase("a"){
occurrences++;
if(occurrences == 2) {
// Do something
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With