小九九 发表于 2023-8-1 14:42:28

Java基础,数组排序

使用java语言,输入一串数字,求,各个数字出现的次数,并按出现次数的大小进行排序。例如,输入次数:1 2 3 4 2 12
输出:2出现次数3,1出现次数2,3出现次数1,4出现次数1





可以使用Java中的`HashMap`来实现这个需求。首先,你需要将输入的数字存储到HashMap中,并统计每个数字出现的次数。然后,你可以使用Java中的排序方法(如`Collections.sort`)对HashMap中的键值对按照值进行排序。

下面是一个示例代码:

```java
import java.util.*;

public class NumberCountSort {
    public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      System.out.println("请输入一串数字:");
      String input = scanner.nextLine();

      // 将输入的数字转换为数组
      String[] numbers = input.split(" ");

      // 使用HashMap统计数字出现次数
      HashMap<String, Integer> countMap = new HashMap<>();
      for (String num : numbers) {
            if (countMap.containsKey(num)) {
                countMap.put(num, countMap.get(num) + 1);
            } else {
                countMap.put(num, 1);
            }
      }

      // 对HashMap中的键值对按值进行排序
      List<Map.Entry<String, Integer>> entryList = new ArrayList<>(countMap.entrySet());
      Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue() - o1.getValue();
            }
      });

      // 输出结果
      for (Map.Entry<String, Integer> entry : entryList) {
            System.out.println(entry.getKey() + "出现次数" + entry.getValue());
      }
    }
}
```

你可以将以上代码保存为`NumberCountSort.java`文件,并在命令行中执行`java NumberCountSort`运行程序。然后输入一串数字(每个数字以空格分隔),即可得到按出现次数排序的结果。
页: [1]
查看完整版本: Java基础,数组排序