所以我想问用户他们是否想从数组列表中删除一个元素。数组列表是从文件读入的喜欢颜色的列表。所以我们可以说数组列表的内容是 - 红色,橙色,绿色,蓝色。我想知道如何删除基于用户输入的元素。它会是这样的 -如何从我的数组列表中删除元素?
System.in.println("Which color would you like to remove")
removeColor = reader.nextString
if removeColor (//using pseudo code here) contains removeColor, remove from ArrayList
我在正确的轨道?继承我的代码到目前为止。谢谢!
Scanner input = new Scanner(System.in);
ArrayList <String> favoriteColors = new ArrayList <String>();
boolean repeat = true;
while (repeat) {
System.out.println("Enter the name of the file which contains your favorite colors ");
String fileName = input.nextLine().trim();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
System.out.println("Here are your favorite colors according to the file:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
favoriteColors.add((line));
}
System.out.println("Add more? (y/n)");
if (input.next().startsWith("y")) {
System.out.println("Enter : ");
favoriteColors.add(input.next());
} else {
System.out.println("have a nice day");
}
for (int i = 0; i < favoriteColors.size(); i++) {
System.out.println(favoriteColors
if (input.next().startsWith("y")) {
System.out.println("Remove a color?")
if (input.next().startsWith("y")) {
/something along the lines of the pseudo code I wrote above
只要调用remove,它将删除元素,如果相同的元素在'List'中或者它不是。 – SomeJavaGuy
是的,你在正确的轨道上。看一看Arraylist文档 - https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html,特别是'remove'方法。 – Matt
一个小提示:如果你正在编写一个程序来保存某人喜欢的颜色列表,你可能不需要'favoriteMovies'变量。 – ajb