3

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.

2
  • Simply use a counter? Commented Apr 9, 2015 at 16:01
  • set up a counter from zero if string is found increase the counter if counter is incresed to 2 do your operatiion Commented Apr 9, 2015 at 16:02

3 Answers 3

4

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
          }
     }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Count the occurences of the searched element and break the loop when you find two occurences:

String[] myStringArray = {"a","b","c","a","d","e","f"};
int count=0;
for(int i=0; i<myStringArray.length;i++){
    if(myStringArray[i].equalsIgnoreCase("a")){
        count++;
    }
    if(count==2){
        System.out.println("the index of the second occurence is:"+ i); 
        break;
    }
}

Take a look at this DEMO.

Comments

0

You can create an int counter initialized by 0, for example, and increment it when you find the first element, so when you get the second element you check the flag and if the flag is set to 1 you do something.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.