首页 > 解决方案 > How do I remove an element the user input from an ArrayList when it contains both strings and integers?

问题描述

I'm new to coding and I'm quite confused of how this ArrayList work.

I have the [Java] code:

ArrayList<Object> allCards = new ArrayList<Object>();

allCards.add(2);
allCards.add(2);
allCards.add(3);
allCards.add('K');
allCards.add('J');

Printing out the allCardsArrayList, I have:

[2, 2, 3, K, J]

Right now, I need to take in an user input, and remove the user input from this ArrayList. How do I do that?

I could use

Scanner scan = new Scanner(System.in);
int i = scan.nextInt();

allCards.remove(new Integer(i));

if the ArrayList only contains integers, but the user input could be either a char or an int, how do I remove that from the ArrayList?

Also, if there are two of the same user input in the ArrayList like the number 2, I would only like to remove one of them.

Thank you.

标签: javaarraylist

解决方案


I think your problem can be solved if you just use ArrayList with String type like:

    ArrayList<String> allCards = new ArrayList<String>();

About how to remove the element in the array list, you can get an input from user in String, then compare it to elements in the array list. When you use the remove() method if the input string matches (case-sensitive) the element, it will only remove the first occurrence, if not, it does not thing. You can test this code:

    ArrayList<String> allCards = new ArrayList<String>();
    allCards.add("2");
    allCards.add("2");
    allCards.add("3");
    allCards.add("K");
    allCards.add("J");

    System.out.println("The Array List before user input: ");
    for (String card : allCards) {
        System.out.print(card + " ");
    }
    System.out.println();
    Scanner scanner = new Scanner(System.in);
    System.out.print("Input to remove from Array List: ");
    String input = scanner.nextLine();
    allCards.remove(input);

    System.out.println("The Array List after user input: ");
    for (String card : allCards) {
        System.out.print(card + " ");
    }
    scanner.close();

推荐阅读