gpt4 book ai didi

Java - 循环遍历ArrayList以扫描匹配值

转载 作者:行者123 更新时间:2023-12-01 09:03:18 30 4
gpt4 key购买 nike

我正在尝试使用 ArrayList 编写一个简单的程序,用于添加值、删除值和打印值。但是,我在删除用户输入的值时遇到问题。用户应该输入指定数量的值(由用户确定),然后程序应该删除这些值(如果有重复项,那么它应该只删除该数字的第一个实例,这很好)。它不会删除这些值,并且在某些情况下会删除一个值。我对我的代码有问题的地方有点困惑。这是我的删除值的代码:

private static void removeVals() {
System.out.println("How many values would you like to remove?");
int amountToRemove = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToRemove + " values:");
for(int i = 0; i < amountToRemove; i++) {
int vals = scanner.nextInt();
if(arrayList.get(i).equals(vals)) {
arrayList.remove(i);
}
}
System.out.println("Values removed");
}

这是我的完整代码:

public class Main {

private static ArrayList<Integer> arrayList = new ArrayList<Integer>();
private static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
printOptions();

int option = scanner.nextInt();
while (option != 0) {
switch(option) {
case 1:
addVals();
printOptions();
option = scanner.nextInt();
break;
case 2:
removeVals();
printOptions();
option = scanner.nextInt();
break;
case 3:
printVals();
printOptions();
option = scanner.nextInt();
break;
case 4:
printOptions();
printOptions();
option = scanner.nextInt();
break;
default:
System.out.println("Not a valid option, please enter again:");
option = scanner.nextInt();
break;
}
}
}

private static void addVals() {
System.out.println("How many values would you like to add?");
int amountToAdd = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToAdd + " values:");
for(int i = 0; i < amountToAdd; i++) {
int vals = scanner.nextInt();
arrayList.add(vals);
}
}

private static void removeVals() {
System.out.println("How many values would you like to remove?");
int amountToRemove = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToRemove + " values:");
for(int i = 0; i < amountToRemove; i++) {
int vals = scanner.nextInt();
if(arrayList.get(i).equals(vals)) {
arrayList.remove(i);
}
}
System.out.println("Values removed");
}

private static void printVals() {
for(int i = 0; i < arrayList.size(); i++) {
System.out.print(arrayList.get(i) + " ");
}
System.out.println();
}

private static void printOptions() {
System.out.println();
System.out.println("Program options: ");
System.out.println("1. Add values\n2. Remove values\n3. Print values\n4. Print options\n0. Exit\n");
System.out.println("\nWhat would you like to do? (enter an option):");
}
}

最佳答案

arrayList.remove(i) 删除此列表中指定位置的元素。将所有后续元素向左移动(从索引中减去 1)。这是你的代码的错误有关更多详细信息,请参阅下面的链接 https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(int) ,

关于Java - 循环遍历ArrayList以扫描匹配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41497523/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com