私の理解が正しければ、このヘッダーを使用してメソッドを実装する必要があります
public static void removeDuplicate(ArrayList<Integer> list)
その名前から判断すると、メソッドはリストから重複を削除する必要があり、(現在行っているように) 入力中に do-while-loop を削除する必要はありません。
したがって、最初にループ ( ) のチェックを外し、if(!list.contains(value)&& value !=0)
ユーザーが入力するすべての番号をリストに追加します。
次に、メソッドを呼び出すことができますremoveDuplicate(list);
。必要に応じて、この呼び出しをループに追加すると、入力ごとに実行されるか、入力が閉じられたときに 1 回だけ実行されます。
メソッドを実装する:
public static void removeDuplicate(ArrayList<Integer> list) { // this is the header you need to use
ここでの問題は、メソッドがリストを認識しているが、重複の可能性がある要素を認識していないことです。だから探せばいい
for (int i = 0; i < list.size(); i++) { // iterate through every element in the list
Integer current = list.get(i); // for convenience, save the current list item in a variable
したがって、リスト内のすべての整数を 1 つずつチェックします。しかし、整数がもう一度存在するかどうかを知りたい場合は、リストの末尾を検索する必要があります。つまり、i の後にサブリストを確認する必要があります。
List sublist = list.subList(i + 1, list.size()); // the sublist with all elements of the list from i+1 to the end
あなたのlist.contains(value)
行は正しいです。ここでも使用できます。サブリストでそれを呼び出すのは今だけです
if(sublist.contains(current)){ // checks if the number is in the sublist
sublist.remove(current); // removes the number from the sublist
}
ただし、これは最初の重複を削除するだけです。current
または、整数に等しいリスト内のすべてのアイテムを削除できます。
while (sublist.contains(current)) {
sublist.remove(current);
}
以上です。あなたの方法は終了しました。
}
}
プログラムで唯一無二のリストに実際に取り組んでいるので、これで終了です。から整数を削除しても、sublist
実際にはsublist
および実数リストから削除されます(sublist
は単なる参照であり、それ自体が実際のリストではありません)。
編集
便宜上、両方のメソッドを含む完全なコードをここに示します。コードを自分のコードと比較すると、それほど違いがないことがわかります。
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
System.out.print("Enter integers (input ends with 0): ");
int value;
do {
value = input.nextInt();
if (value != 0) { // this changed: add every number except 0
list.add(value);
}
} while (value != 0);
input.close();
removeDuplicate(list); // here you make the call for the new method
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
}
// and this is the new method
public static void removeDuplicate(ArrayList<Integer> list) {
for (int i = 0; i < list.size(); i++) {
Integer current = list.get(i);
List sublist = list.subList(i + 1, list.size());
while (sublist.contains(current)) {
sublist.remove(current);
}
}
}