有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组中total的java排序

我试图列出文本文件中的所有内容,然后通过忽略每行中的第一个元素并按降序排序来计算每个元素的数量。我不知道该怎么分类

文本文件的内容:

1,2,8,4,5,6,7,7

3,4,5,6,7,8,3

5,6,7,8,9,9

我希望预期结果如下所示:

考试[1]:2845677

计数:7

考试[3]:45678

计数:5

考试[5]:67893

计数:6

分类:

如何按降序排列计数7、计数6和计数5

我已尝试使用此排序:

private static void sortInDescending(int[] num){

    int n = num.length;
    int temp = 0;

    for(int i = 0; i < n; i++) {

        for(int j = 1; j < (n-i); j++) {

            temp = num[j-1];
            num[j-1] = num[j];
            num[j] = temp;

        }
    }
}

但这种排序是按降序对每行中的每个元素进行排序

这是我迄今为止所做的编码:

Scanner scanner = new Scanner(new File("test.txt"));
int row = 0;
int count = 0;

while(scanner.hasNextLine()) {
    String currentline = scanner.nextLine();

    row++;

    String[] items = currentline.split(",");
    int[] intitems = new int[items.length];
    int i = 0;

    for(i = 0; i < items.length; i++) {
        intitems[i] = Integer.parseInt(items[i]);

        if(i == 0) {

            System.out.print("Exam[" +intitems[i]+ "] ");
        } else {

            System.out.print(intitems[i]+ " ");
            count++;
        }
    }

    System.out.println("\nCount " +count);
    count = 0;
}

共 (1) 个答案

  1. # 1 楼答案

    下面是如何排序数组,而不是使用Arrays自己排序

    //initialize the array which you want to sort
    //in your case it would be `exam` or `count` array
    //Pass the array as an argument to sort method, for example
    int[] s = new int[10];         //initialize it with values
    Arrays.sort(s);                //this will sort it in ascending order
    System.out.println(Arrays.toString(s));   //to print it
    

    现在,如果要反转它,请使用for循环并从最后一个索引到第一个索引读取数组。我相信你能做到