简体   繁体   中英

Remove object from array list with user input

If i have 10 objects in an array list and i want to remove a specific one based on the userinput, how do i do it?

public ArrayList<SmallItem> Backpack = new ArrayList<SmallItem>();
Scanner t = new Scanner(System.in);
String userInput = t.next();

public void dropItemByName() {
    if(Backpack.contains(t)) {
          Backpack.remove(item);
        }

    }

You don't want to check Backpack.contains(t) unless you're actually searching for t in Backpack . t is your Scanner object itself, not the input.

If you want the user to input the index of an object to be removed, then you'll want to make userInput an int and do this:

if (userInput < Backpack.size()) {
    Backpack.remove(userInput);
}

If you want the user to input the name or some other input referring to the object rather than its index, then you should write a method that takes userInput as a parameter and determines which SmallItem is to be removed from Backpack and removes it.

Here's an example of how that could be done if each SmallItem has a variable name of type String :

for (int i=0; i<Backpack.size(); i++) {
    if (Backpack.get(i).name.equals(userInput) {
        Backpack.remove(i);
        break;
    }
}

This example would remove the first SmallItem in Backpack that has a name that matches userInput . If you want it to remove every SmallItem in Backpack with that name value instead of just the first one, just remove the break statement.

If i get it write I think you want to remove the item (t) from the list

So you have to change the variable (item) by the variable (t or user input) as shown below:

String userInput = t.nextline();

public void dropItemByName() {

if(Backpack.contains(userInput)) {
      Backpack.remove(userInput);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM