我一直在开发一个可以让你输入披萨配料的程序。除了removeToppings() 方法之外,它已经非常完整了。
问题是,我似乎无法找出删除用户选择的索引中的配料以及之前的所有配料的正确方法。我找到了多种方法来删除之后出现的索引,但即便如此,我也找不到反转它们的方法。
这是有问题的方法:
public static void removeTopping()
{
Scanner in = new Scanner(System.in);
printPizza();
System.out.println("What topping do you want to remove?\n"
+ "Keep in mind, this loses everything else above it.\n"
+ "Enter index number: ");
int remove = in.nextInt();
toppings.subList(remove, toppings.size()).clear(); //this is the problem line!
}
printPizza() 方法将打印如下所示的内容:
|index|topping|
| 0 | cheese
| 1 | three
| 2 | cheese
| 3 | two
| 4 | cheese
| 5 | one
| 6 | sauce
| 7 | crust
假设我输入 5,程序将删除索引 5、6 和 7。我希望它删除 0-5。任何指示将不胜感激。
最佳答案
您可以使用 for 循环来实现此目的。
循环将从删除 remove
变量指定的索引开始。然后,循环将递减 i
直到达到 -1,此时,它将删除您设置的索引以下的所有元素。
for (int i = remove; i > -1; i--) {
myList.remove(i);
}
关于java - 我将如何使用 ArrayList 删除用户在 Java 中指定的索引之前(而不是之后!)的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60492180/