Reputation: 27
I am having an issue when comparing elements in two int arrays. I am using a for loop to compare each element in the two arrays, and if the elements match, the boolean result is to return true, and if not, return false. The problem is that it is always returning true, regardless of whether they match or not.
Entire program here http://pastebin.ca/2626244
the loop:
boolean result;
int counter = 0;
//compares answers[] to key[]
for (int i = 0; i < size; i++) {
if (answers[i] == key[i]) {
result = true;
}
if (answers[i] != key[i]) {
result = false;
}
if (result = true) {
counter++;
}
}
System.out.println(counter+"/"+size+" questions are correct.");
As a result, "counter" is always the same value as the total elements ("size"). Even if both arrays contain completely different values, the result still will not be 0/size. It always seems to be size/size.
Am I comparing the arrays incorrectly (see full program), or is there just something wrong with my loop?
Upvotes: 1
Views: 1911
Reputation: 4923
= is use to assign the value and to compare the value use `==`
So need to change below code :
if (result == true) {
counter++;
}
or better solution is
if (result) {
counter++;
}
Upvotes: 1
Reputation: 178263
Use the comparison operator ==
to compare things, not the assignment operator =
. But because result
is a boolean
already, just use the boolean
itself.
Change
if (result = true) {
to
if (result)
Upvotes: 2