【问题标题】:How do I remove an element the user input from an ArrayList when it contains both strings and integers?当 ArrayList 同时包含字符串和整数时,如何删除用户输入的元素?
【发布时间】:2020-06-23 05:25:51
【问题描述】:

我是编码新手,我对这个 ArrayList 的工作方式感到很困惑。

我有 [Java] 代码:

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

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

打印出allCardsArrayList,我有:

[2, 2, 3, K, J]

现在,我需要接收用户输入,并从这个 ArrayList 中删除用户输入。我该怎么做?

我可以使用

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

allCards.remove(new Integer(i));

如果 ArrayList 仅包含整数,但用户输入可以是 char 或 int,我如何从 ArrayList 中删除它?

另外,如果 ArrayList 中有两个相同的用户输入,比如数字 2,我只想删除其中一个。

谢谢。

【问题讨论】:

  • 注意:你应该使用工厂方法Integer.valueOf来支持构造函数。这利用了整数缓存,提供了性能提升。
  • @MCEmperor 或者只是传递 i,这正是这样做的。
  • @MauricePerry 不,那行不通,因为remove(Object o)方法被remove(int index)重载了,它不会删除指定的对象,而是删除位于而是指定的索引。我承认这是一个令人讨厌的问题,但这对于这个特殊情况很重要。在这种情况下,如果 i 具有值 3 并且调用了 allCards.remove(i),则将删除 K。
  • @MCEmperor 好的。我的错。

标签: java arraylist


【解决方案1】:

我认为如果你只使用带有 String 类型的 ArrayList 就可以解决你的问题:

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

关于如何删除数组列表中的元素,你可以从用户那里得到一个String中的输入,然后将它与数组列表中的元素进行比较。当您使用 remove() 方法时,如果输入字符串匹配(区分大小写)元素,它只会删除第一个匹配项,如果不匹配,则不会。你可以测试这段代码:

    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();

【讨论】:

    【解决方案2】:

    因此,您希望能够从输入中读取int 或char。我猜你必须为你的输入字符串定义一个语法,这样你就可以决定它是int还是char。您可以为此使用正则表达式。

    例子:

    private static final Pattern RE
            = Pattern.compile("^\\s*(?:([0-9]+)|'(.)')\\s*");
    
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        Matcher matcher = RE.matcher(s);
        if (!matcher.matches()) {
            System.out.println("Bad input");
        } else {
            Object key;
            if (matcher.group(1) != null) {
                key = Integer.valueOf(matcher.group(1));
            } else {
                key = matcher.group(2).charAt(0);
            }
            allCards.remove(key);
            System.out.println(allCards);
        }
    

    【讨论】:

      【解决方案3】:

      这个问题有两个部分,首先你需要正确读取一个字符或一个整数,然后将其从列表中删除。 首先逐行转换为int或char,然后使用迭代器循环遍历列表并删除对象并中断。

      public static void main(String[] args) {
              List<Object> allCards = new ArrayList<>();
              allCards.add(2);
              allCards.add(2);
              allCards.add(3);
              allCards.add('K');
              allCards.add('J');
              Scanner scan = new Scanner(System.in);
              while (true) {
                  String line = scan.nextLine();
                  try {
                      int num = Integer.parseInt(line);
                      for(Iterator<Object> it = allCards.iterator(); it.hasNext(); ) {
                          Object o = it.next();
                          if ((o instanceof Integer) && (Integer) o == num) {
                              allCards.remove(o); break;
                          }
                      }
                  } catch (Exception ex) {
                      char c = line.charAt(0);
                      for(Iterator<Object> it = allCards.iterator(); it.hasNext(); ) {
                          Object o = it.next();
                          if ((o instanceof Character) && (Character) o == c) {
                              allCards.remove(o); break;
                          }
                      }
                  }
              }
          }
      

      您可以扩展它以支持更多对象类型。

      【讨论】:

      • 为什么要遍历列表而不只是调用remove(Object)?
      • 我想扩展它以支持更多的整数和字符对象。由于 Objects.equals 仅检查参考,因此无法正常工作。但事实证明,记住 OP 的问题是不必要的努力。
      【解决方案4】:

      假设您无法更改数组 allCards 的类型,您必须将输入转换为 Integer 和 Character 并检查它们是否包含在列表中:

              final List<Object> allCards = new ArrayList<Object>();
      
              allCards.add(2);
              allCards.add(2);
              allCards.add(3);
              allCards.add('K');
              allCards.add('J');
      
              final Scanner scanner = new Scanner(System.in);
              final String i = scanner.nextLine();
      
              try {
                  allCards.remove(Integer.valueOf(i));
              } catch(NumberFormatException e) {
                  // safe to ignore
              }
              allCards.remove(Character.valueOf(i.charAt(0)));
              
              scanner.close();
      

      但是,如果您正在实现某种纸牌游戏,您应该考虑引入卡片类型的类或枚举,并使用强类型的卡片列表。比如这样:

          final List<Card> allCards = new ArrayList<Card>();
          allCards.add(new Card(CardValue.C2));
          allCards.add(new Card(CardValue.C2));
          allCards.add(new Card(CardValue.C3));
          allCards.add(new Card(CardValue.CK));
          allCards.add(new Card(CardValue.CJ));
      
          playCard(allCards);
      
          System.out.println("The Array List after user input: ");
          for (Card card : allCards) {
              System.out.print(card.getValue() + " ");
          }
      
          private void playCard(List<Card> allCards) {
              final Scanner scanner = new Scanner(System.in);
              final String i = scanner.nextLine();
              scanner.close();
      
              final CardValue cardValue = CardValue.getCardValue(i);
              final Optional<Card> foundCard = allCards.stream().filter(c -> c.getValue() == cardValue).findAny();
      
              if (foundCard.isPresent()) {
                  allCards.remove(foundCard.get());
              } else {
                  throw new IllegalArgumentException("You have no card with value " + i);
              }
      
          }
      
          private class Card {
              private final CardValue value;
      
              private Card(CardValue value) {
                  this.value = value;
              }
      
              private CardValue getValue() {
                  return value;
              }
      
          }
      
          private enum CardValue {
              C2("2"),
              C3("3"),
              // all other values ...
              CJ("j"),
              CK("k");
      
              private final String value;
      
              CardValue(String value) {
                  this.value = value;
              }
      
              public CardValue getCardValue(String value) {
                  for (CardValue c : CardValue.values()) {
                      if (c.value.equals(value.toLowerCase().substring(0, 1))) {
                          return c;
                      }
                  }
                  throw new IllegalArgumentException("Illegal card value " + value);
              }
          }
      

      玩得开心!

      【讨论】:

        【解决方案5】:

        你可以使用Collection.removeIf:

        allCards.removeIf(obj -> obj instanceof Integer);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-12-31
          • 2016-05-24
          • 2018-06-21
          • 1970-01-01
          • 2017-01-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多