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
  }
}
0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And it complies to Java's naming conventions (arr could have been called array though).
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

Comments

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

2 Comments

working but you have to explain why his code is not working
Well I can give you a link that might help you understand it better: stackoverflow.com/questions/30033035/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.