java - 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 allCards
ArrayList, 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.
解决方案
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();
推荐阅读
- django - 嵌套循环访问字典 Django HTML
- excel - 复制和粘贴特殊而不选择单元格
- javascript - DOMException: 未能执行 styleSheet.insertRule
- python - 按切片编辑数据框
- azure - Azure Kusto - 如何解析寻找最后一个节点的字符串?
- php - 使用 phpmailer 将 html 表单转换为 pdf 和电子邮件
- mysql - 正则表达式 varchar 的 Mysql 订单无法正常工作
- java - 如何在 JPA 中使用规范
- arm - gdb 目标架构尚未列出似乎受支持..?
- android - Android错误将现有数据库导入项目