简体   繁体   English

将索引处的字符串数组与字符串进行比较

[英]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 我有一些Java代码,我在其中定义一个数组,然后用这样的值填充它

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 在代码的后面,用不同的非“ moo”字符串填充了数组的前几个插槽后,我进行了比较

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)... ...但是每当"moo".equals(longestSequences[counter])返回true(计数器初始化为0,并且我已经使用print语句检查该数组是否确实包含不是moo的字符串)在此while循环之前)...

I've tried using equals(longestSequences[counter],"moo") but then the compiler complains that I'm use an object method on strings! 我试过使用equals(longestSequences[counter],"moo")但是编译器抱怨我在字符串上使用对象方法! In particular, it gives me this error 特别是它给了我这个错误

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

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. 最可能的原因是: counter的值在整个循环中保持稳定,因此,您始终将“ moo”与某些固定单元格的值进行比较。 If that cell happens to hold "moo" then you're bound to get true on every iteration. 如果该单元格恰好保持“ moo”,那么您肯定在每次迭代中都为true

Bottom line: make sure counter is changed in your loop. 底线:确保counter已在循环中更改。

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. 我什至更进一步地说,您并不是真的想与longestsequences[counter] bur进行比较,而是与longestsequences[i]进行比较,在循环开始之前, i应该将其初始化为零,并且每次循环迭代都将其增加。

As for equals(longestSequences[counter],"moo") - this cannot work. 至于equals(longestSequences[counter],"moo") -这是行不通的。 The equals method is an instance method that takes a single parameter. equals方法是采用单个参数的实例方法。 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) . 因此,如果要比较X与Y,则应编写X.equals(Y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM