所以我想問用戶他們是否想從數組列表中刪除一個元素。數組列表是從文件讀入的喜歡顏色的列表。所以我們可以說數組列表的內容是 - 紅色,橙色,綠色,藍色。我想知道如何刪除基於用戶輸入的元素。它會是這樣的 -如何從我的數組列表中刪除元素?
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