我想開發一個程序,可以通過字符串進行排序並刪除重複項。我爲此使用嵌套循環。但是,當我運行我的代碼時,它只是重複幾遍。刪除帶有嵌套循環的重複項java
package q2;
import java.util.Arrays;
public class Q2 {
public static void main(String[] args) {
String sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY";
String lowercaseSentence;
lowercaseSentence = sentence.toLowerCase();
String[] sentenceWords = lowercaseSentence.split(" ");
int LenghtofSentence = sentenceWords.length;
String[] unique = new String[LenghtofSentence];
for (int i = 0; i <= LenghtofSentence; i++) {
//System.out.println(i);
for (int j = 0; j <= LenghtofSentence; j++) {
if (!sentenceWords[i].equals(unique)) {
unique[j] = sentenceWords[i];
j++;
} else {
j++;
}
}
System.out.println(Arrays.toString(unique));
}
}
}
這是錯誤消息我得到:
[ask, null, ask, null, ask, null, ask, null, ask, null, ask, null, ask, null, ask, null, ask]
[not, null, not, null, not, null, not, null, not, null, not, null, not, null, not, null, not]
[what, null, what, null, what, null, what, null, what, null, what, null, what, null, what, null, what]
[your, null, your, null, your, null, your, null, your, null, your, null, your, null, your, null, your]
[country, null, country, null, country, null, country, null, country, null, country, null, country, null, country, null, country]
[can, null, can, null, can, null, can, null, can, null, can, null, can, null, can, null, can]
[do, null, do, null, do, null, do, null, do, null, do, null, do, null, do, null, do]
[for, null, for, null, for, null, for, null, for, null, for, null, for, null, for, null, for]
[you, null, you, null, you, null, you, null, you, null, you, null, you, null, you, null, you]
[ask, null, ask, null, ask, null, ask, null, ask, null, ask, null, ask, null, ask, null, ask]
[what, null, what, null, what, null, what, null, what, null, what, null, what, null, what, null, what]
[you, null, you, null, you, null, you, null, you, null, you, null, you, null, you, null, you]
[can, null, can, null, can, null, can, null, can, null, can, null, can, null, can, null, can]
[do, null, do, null, do, null, do, null, do, null, do, null, do, null, do, null, do]
[for, null, for, null, for, null, for, null, for, null, for, null, for, null, for, null, for]
[your, null, your, null, your, null, your, null, your, null, your, null, your, null, your, null, your]
[country, null, country, null, country, null, country, null, country, null, country, null, country, null, country, null, country]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 17
我使用此NetBeans。任何幫助表示讚賞。 謝謝 Keir
調試你的代碼。 – f1sh
爲什麼不使用'Set'(例如'LinkedHashSet')? – Thomas
當你像這樣編寫一個for循環時:for(int i = 0; i <= LenghtofSentence; i ++)'你要經過數組的末尾。它應該是'<'而不是'<='。 – khelwood