文字列をソートして重複を削除できるプログラムを開発しようとしています。私はこれのためにネストされたループを使用しています。しかし、私は私のコードを実行すると、何度も何度も何度も繰り返します。ネストされたループで重複を削除する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