I attempted writing a piece of Java code to check if there were multiple occurrences of a substring in another string, so if a substring appeared more than once in a string the method ought to return true, else it should return false. It worked fine when the substring was not present at all in the string but it returned true when the substring was present but did not occur more than once which isn’t supposed to happen. Below is method:
public boolean twoOccurrencesMethod(String a, String b){
int fromIndex = 0;
int count = 0;
int Index = b.indexOf(a, fromIndex);
while((Index) != -1){
count++;
fromIndex = Index + 1;
if (count > 1){
return true;
}
}
return false;
}
I expected the method to return false when the substring did not occur more than once in the string.
But with a bit of tinkering, I arrived at the below method which works perfectly.
public boolean twoOccurrencesMethod(String a, String b){
int fromIndex = 0;
int count = 0;
int Index;
while((Index = b.indexOf(a, fromIndex)) != -1){
count++;
fromIndex = Index + 1;
if (count > 1){
return true;
}
}
return false;
}
Why exactly does initializing the Index variable in the condition of the while loop work as opposed to initializing it before the while loop like in the first method?
>Solution :
Why exactly does initializing the Index variable in the condition of the while loop work as opposed to initializing it before the while loop like in the first method?
In the first snippit of code, you assign Index once. In the second, you assign the new value every loop.
Once you assign a value to a variable, it will only ever change if you reassign it. In the first code, Index only ever be the value of b.indexOf(a, fromIndex), even the second time through the loop. It doesn’t automatically update when you change fromIndex, you have to tell it to recalculate (which you did when you put the assignment inside of while((Index = b.indexOf(a, fromIndex)) != -1)).
Since Index never changes, then Index != -1 never changes. Which means the while loop will always either be while (false), in which case it skips it entirely, or while (true), which would cause two iterations, raising count to be above 1, causing the return true.
Effectively, your first snippit just does this:
public boolean twoOccurrencesMethod(String a, String b) {
int Index = b.indexOf(a, 0);
if (Index != -1) {
return true;
}
return false;
}