【问题标题】:Sort an Array List based on user input?根据用户输入对数组列表进行排序?
【发布时间】:2017-05-04 19:50:29
【问题描述】:

所以我有一个数组列表,其中包含最喜欢的颜色列表。例如,数组读取为 - 红、蓝、绿。但现在我希望用户能够“排名”他们最喜欢的颜色,因为当前列表不是他们的个人排名。那么我如何将数组列表的一个元素向下移动到另一个位置。我想让程序说“列表上的第一项是红色的,你会把它排在哪里?”然后他们可以说他们想要它在第三个位置。然后以此类推,直到他们对所有这些进行排名。问题是我是数组列表的新手,不知道该怎么做。我会使用 Collections.sort(array list); ?我什至如何调用数组的元素来询问它们?是不是类似于(在此处使用伪代码)数组列表的第 1 行/第 1 行?

到目前为止的代码(最后一部分并不能正常工作,但你会看到我想要去哪里)

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 {
                     break;
                 }
                 for (int i = 0; i < favoriteColors.size(); i++) {
                     System.out.println(favoriteColors);
                 }

                     System.out.println("Remove a color?");

                     if (input.next().startsWith("y")) {
                         System.out.println("Which color would you like to remove");
                            String removeColor = input.nextLine();
                            int index = favoriteColor.indexOf(removeColor);
                            favoriteColor.remove(index);
                            System.out.println(favoriteColor);
                     }

谢谢

【问题讨论】:

  • 你能发布你所做的代码吗?至少发布用于初始化数组列表的代码。你使用的是 python 列表、numpy 数组还是数组?
  • @imp9 刚刚添加了我的代码

标签: arrays sorting arraylist


【解决方案1】:

“我想让程序说‘列表中的第一项是红色的,你会把它排在哪里?’然后他们可以说他们想要它排在第三位。然后以此类推,直到他们对所有这些人进行排名。”

为此,您需要创建一个新列表,该列表的长度与原始列表相同,但其中的每个值都是一些空颜色,然后您将遍历原始列表,询问他们对每个列表的排名颜色,并将颜色插入到他们将对其进行排名的位置。您可以使用“.get(index)”从数组列表中获取值。一个例子:
ArrayList a = new ArrayList(); a.get(5)

这在技术上会引发错误,因为 a 在索引 5 处没有元素,但这不是本示例的重点。

【讨论】:

  • 谢谢您,跟进 - 有没有一种简单的方法可以使新列表的长度与原始列表的长度相同?因为它不是一个固定的数量 - 他们可以添加颜色或减去一个
  • 有一种简单的方法可以找出当前列表的长度。它被称为“.size()”。这是 ArrayList 的文档,您可以看到为其定义的所有函数。 docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
猜你喜欢
  • 1970-01-01
  • 2020-11-17
  • 2021-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
相关资源
最近更新 更多