1

I am trying to find a character array inside of a character array so that in the array, A would be followed by B. For some reason, I do not get an error but I also cannot get it to do the work I want when I have an array with the combination. I was just wondering if someone could explain what I am doing wrong and point me in the right direction.

char[] Array = new char[] {'A','B','C','D'....};
char A = 'A';
char B = 'B';
....
for (int i = 0 ; i < Array.length; i ++) {
  if (Array[i] == A && Array[i++] == B) {
    //Work Here
  }
}
gudok
  • 4,029
  • 2
  • 20
  • 30
David
  • 13
  • 2

3 Answers3

4

First, ont to make i + 1 exceed array indexes, use i < arr.length - 1 in for loop. Then, change arr[i++] to arr[i+1] in if statement.

char[] arr = new char[] {'A','B','C','D'....};
char a = 'A';
char b = 'B';
....
for (int i = 0 ; i < arr.length - 1; i++) {
    if (arr[i] == a && arr[i+1] == b) {
        //Work Here
    }
}

P.S: prop names are switched from capital case on purpose, to be consistent with the Java naming conventions.

vahdet
  • 6,357
  • 9
  • 51
  • 106
0

While I like aproaches in other answers so far better. If you want to stick to your approach, you need the correct increment operator ( and also take care that the index doesn't exceed bounds):

for (int i = 0 ; i < Array.length-1;) {
  if (Array[i++] == A && Array[i] == B) {
    //Work Here
  }
}

For the one guy that doesn't believe it works, a run with some data:

public static void main(String... args) {
    char[] Array = new char[]{'A', 'B', 'C', 'D', 'A', 'B','C', 'D', 'B','A', 'A'};
    char A = 'A';
    char B = 'B';
    for (int i = 0; i < Array.length - 1;) {
        if (Array[i++] == A && Array[i] == B) {
            System.err.println("found at index;" +i);
        }
    }
}

output:

found at index;1
found at index;5

qed

kai
  • 894
  • 1
  • 7
  • 15
0

The problem is in here: Array[i++] == B, that is i++ is a post increment which means it is first evaluated to i then it is incremented by 1.

if i=0 for example, Array[i++] == B gives you Array[0] == B, then after that i=1

to solve the issue: use Array[i+1] == B or Array[++i] == B instead

read here

So, i++ returns i but it increments i by 1

The Scientific Method
  • 2,374
  • 2
  • 14
  • 25