Zach
Zach

Reputation: 75

Comparing String Array at an index with a String

I have some java code where I define an array and then fill it with values like this

String[] longestSequences = new String[40];
Arrays.fill(longestSequences,"moo");

Later on in the code, after I've filled the first several slots in the array with different, non-"moo" strings, I do a comparison

while (!"moo".equals(longestSequences[counter]));

...but every time "moo".equals(longestSequences[counter]) returns true (counter is initialized to 0, and I've used print statements to check that the array does indeed have strings that aren't moo in it right before this while loop)...

I've tried using equals(longestSequences[counter],"moo") but then the compiler complains that I'm use an object method on strings! In particular, it gives me this error

DNA.java:54: error: method equals in class Object cannot be applied to given types

Upvotes: 0

Views: 394

Answers (1)

Itay Maman
Itay Maman

Reputation: 30733

Most likely cause: the value of counter is steady throughout your loop, thus you're always comparing "moo" with the value of some fixed cell. If that cell happens to hold "moo" then you're bound to get true on every iteration.

Bottom line: make sure counter is changed in your loop.

I'd go even further to say that you don't really want to compare with longestsequences[counter] bur rather with longestsequences[i] where i should be initialized to zero before the loop starts and it is increased with every iteration through the loop.

As for equals(longestSequences[counter],"moo") - this cannot work. The equals method is an instance method that takes a single parameter. It compares the parameter with the instance on which this method was called (that is: with the object at the left side of the dot .). Thus, if you want to compare X with Y, you should write X.equals(Y).

Upvotes: 1

Related Questions