我希望获取一个整数数组并对照两个数字进行检查,第一个数字是我要替换的数组中的数字,第二个数字是我希望替换第一个数字的数字。我已经设法编写代码来破坏性地和建设性地执行此操作,但我只想将第一次输入的数字的第一次出现更改为第二个数字,而不是所有条目。
例如,如果我输入 {3, 5, 1, 3, 6} 和 3 作为我想要替换的数字,9 作为我想要替换的数字,我应该得到 {9, 5 , 1, 3, 6} 因为我只想将 3 的第一次出现更改为 9,而不是两者都更改。
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;
}*/
}
我也对 main 方法中将用户输入添加到 ArrayList 中的代码感到好奇。有没有更好的方法,不需要用户输入 999
即可跳出 while
循环。
最佳答案
在 if 中添加一个break语句:
if (list.get(i) == numberCompare) {
list.set(i, numberReplace);
break;
}
这样循环将在条件第一次为真时被中断。
关于java - 如何在 Java 中仅更改 ArrayList 中第一次出现的对象,忽略后续的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46837739/