How would I go about removing indexes that come before (not after!) an index stated by the user in Java using ArrayLists?

emmie o :

I've been working on a program that lets you enter pizza toppings. It's pretty much complete, except for the removeToppings() method.

The problem is, I can't seem to figure out the correct way to remove the toppings in the index that the user chooses and all of the toppings BEFORE it. I have found numerous ways to remove indexes that come AFTER, but even then I can't find ways to reverse them.

Here's the method in question:

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!
    }

The printPizza() method would print something that looks like this:

|index|topping|
|  0  | cheese
|  1  | three
|  2  | cheese
|  3  | two
|  4  | cheese
|  5  | one
|  6  | sauce
|  7  | crust

Say I enter 5, the program would remove indexes 5, 6, and 7. I would want it to remove 0-5. Any pointers would be much appreciated.

rhowell :

You can use a for loop to achieve this.

The loop will start by removing the index specified by the remove variable. Then, the loop will decrement i until it reaches -1, by this point, it will have removed every element below the index you set.

    for (int i = remove; i > -1; i--) {
        myList.remove(i);
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=20314&siteId=1