[英]Compare string array values in Java
我試圖將字符串數組中的每個值與同一數組的所有值進行比較,以查看它們是否相等(類似於“wordA”等於“wordA”)。 這就是我所擁有的:
FileReader input;
input = new FileReader("file.txt");
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
String[] text = line.replaceAll("[^a-zA-Z ]", "").split("\\s+");
for (int A = 0; A < text.length; A++) {
for (int B = text.length; B > 0; B++){
if (text[A].equals(text[B])){
System.out.println("Repeated Word: "+text[A]);
}
}
}
它只是比較數組空間,因此如果 A 和 B = 3(例如),它將始終為真,忽略此空間內的字符串。 所以我將文本中的所有單詞作為輸出。
第二個 for 循環有問題,你會得到一個數組索引越界。
相反,您也應該從頭開始並排除索引是否相等
String[] text = { "a", "b", "c", "d", "a" };
for (int a = 0; a < text.length; a++) {
for (int b = 0; b < text.length; b++) {
if (text[a].equals(text[b]) && a != b) {
System.out.println("Reapeated word : " + text[a]);
}
}
}
或者如評論中所建議的,從數組中的下一個元素開始(在這種情況下,您不必檢查索引是否相等)
String[] text = { "a", "b", "c", "d", "a" };
for (int a = 0; a < text.length; a++) {
for (int b = a + 1; b < text.length; b++) {
if (text[a].equals(text[b])) {
System.out.println("Reapeated word : " + text[a]);
}
}
}
看起來嵌套循環應該是 B-- 而不是 B++。 那不會是一個永無止境的循環嗎? 無論哪種方式,我都認為沒有理由在每個循環中以相反的方向進行迭代。 但每個人都有自己的。
此外,應該進行某種比較以確保 A != B,否則您將比較數組中的相同值。 if (text[A].equals(text[B]))
會在某個時候比較if (text[0].equals(text[0]))
, if (text[1].equals(text[1]))
等。
對於數組中的每個元素,這將始終至少返回一次 true。
您需要添加if (A != B)
來修復它。
像這樣:
for (int A = 0; A < text.length; A++) {
for (int B = 0; B < text.length; B++) {
if (A != B && text[A].equals(text[B])) {
System.out.println("Repeated word:" + text[A]);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.