Reputation: 87
int MATCH_LENGTH = 0;
int FINAL_MATCH_LENGTH = 0;
int FINAL_MATCH_POS = 0;
while (window.contains(next)) {
int MATCH_POS = window.indexOf(next);
boolean nextMatches = true;
while (nextMatches = true) {
int index = window.indexOf(next);
index++;
int positionOfNext = fileArray.indexOf(next);
positionOfNext++;
MATCH_LENGTH++;
char afterNext = fileArray.get(positionOfNext);
char afterNextInWindow = window.get(index);
if (afterNext != afterNextInWindow) {
nextMatches = false;
if (MATCH_LENGTH > FINAL_MATCH_LENGTH) {
FINAL_MATCH_POS = MATCH_POS;
FINAL_MATCH_LENGTH = MATCH_LENGTH;
MATCH_LENGTH = 0;
}
window.remove(window.indexOf(next));
}
}
}
I am running into an infinite loop here. I think it is because of the nextMatches
boolean variable. However, I am not sure how that affects the program, as I have the condition for the while
loop as while (window.contains(next))
. However, I am removing the occurrences of next
one by one, so eventually while (window.contains(next))
will have to return false and the while
loop will have to break. My reasoning here might be flawed though with the remove line window.remove(window.indexOf(next));
.
Or is some other part of my reasoning flawed?
Upvotes: 2
Views: 184
Reputation: 13872
while (nextMatches == true) {
This condition will be false
iff nextMatches
is assigned with false
.
The only place you are assigning it false
, is in following code block:
if (afterNext != afterNextInWindow) {
nextMatches = false;
...
Since, while
is running infinite for you, it means nextMatches
is never assigned with false
when code executes, i.e if
condition is always false
.
This means, that in every iteration of while
; afterNext
is always equals to afterNextInWindow
.
Upvotes: 2
Reputation: 53881
You made the classic =
vs ==
mistake
while (nextMatches = true)
should be
while(nextMatches)
As a general rule, don't compare booleans to true
and false
. It just leads to these sort of weird bugs and makes the code less legible in my opinion. If you name your variables properly, Java conventions has booleans sound like a conditional. For example: isEmpty
or isFull
. This way things read like english: while(isFull)
I'm a bit confused on your logic, especially since int index = window.indexof(next)
will not change anything. index will be redefined.
Upvotes: 7
Reputation: 87
I found the problem. It was this line: int index = window.indexOf(next);
.
I kept on redefining index
as the same number over and over again, which caused the infinite loop. Problem solved!
Upvotes: 2
Reputation: 18651
The problem is here while (nextMatches = true)
try put instead
while (nextMatches == true)
Upvotes: 4