整数の配列を2つの数値と照合したいと思います。その最初の数字は配列の番号です置き換えたいと思って、2番目の番号は最初の番号を置き換える番号です。私はこれを破壊的かつ建設的に行うためのコードを書くことに成功しましたが、すべてのエントリーではなく、最初の数字を最初の数字に変更したいだけです。ArrayList内のオブジェクトの最初のオカレンスだけを変更し、後続の重複を無視する方法
たとえば、交換したい番号として{3,5,1,3,6}と3を入力し、それを置き換えたい番号として9を入力すると、{9、私は最初の出現を3から9のどちらかに変更したいだけで、両方ともではないので、5,1,3,6}
import java.util.*;
public class Ex6 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter some numbers. When you're done, type 999");
boolean cont = true;
while (cont == true) {
int x = scanner.nextInt();
if (x == 999) {
cont = false;
} else {
list.add(x);
}
}
System.out.println("Enter a number to replace");
Scanner sc = new Scanner(System.in);
int numberCompare = sc.nextInt();
System.out.println("Enter the number you want to replace it with");
Scanner sc2 = new Scanner(System.in);
int numberReplace = sc2.nextInt();
changeD(list, numberCompare, numberReplace);
System.out.println(Arrays.toString(list.toArray()));
//System.out.println(changeC(list, numberCompare, numberReplace));
}
public static ArrayList<Integer> changeD(ArrayList<Integer> list, int numberCompare, int numberReplace) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == numberCompare) {
list.set(i, numberReplace);
}
}
return list;
}
/*I am only using one method at a time, depending on what I wish to
test. The above changes
destructively and below changes constructively*/
/*public static ArrayList<Integer> changeC(ArrayList<Integer> list, int
numberCompare, int numberReplace) {
ArrayList<Integer> b = new ArrayList<Integer>();
for(int i = 0; i<list.size(); i++) {
int x = list.get(i);
b.add(x);
}
for(int j = 0; j<b.size(); j++) {
if(b.get(j) == numberCompare) {
b.set(j, numberReplace);
}
}
return b;
}*/
}
また、ユーザー入力をArrayListに追加するメインメソッドのコードについては興味があります。より良い方法はありますか?while
ループから脱出するには、ユーザが999
を入力する必要はありません。ループは、条件が真である最初の時間を中断することになるその方法
if (list.get(i) == numberCompare) {
list.set(i, numberReplace);
break;
}
:
'list.set'の呼び出しの後に' break; 'を追加します。 –