-1

I am trying to list all the content in a text file then calculate the number of each element by ignoring the first element in each row and sort it in descending order. I don't know how can i sort it.

The content of the text file :

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

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

5,6,7,8,9,9,

I want the expected result to like this :

Exam[1] : 2 8 4 5 6 7 7

count : 7

Exam[3] : 4 5 6 7 8

count : 5

Exam[5] : 6 7 8 9 9 3

count : 6

Sorted :

How can i sort count 7, count 6 and count 5 in descending order ?

I have tried using this sorting :

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;

        }
    }
}

But this sort is to sort each element in each row in descending order.

This is my coding that i done so far :

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;
}
ug_
  • 11,267
  • 2
  • 35
  • 52
Jen
  • 31
  • 6
  • 1
    Why not use `Arrays` class? It has overloaded `sort` methods which sorts the passed array in ascending order. Once this is done, read the sorted array in reverse order. – Tirath Oct 14 '14 at 09:27
  • U mean use Arrays class to count the total number of each element in each row ? – Jen Oct 14 '14 at 09:53
  • No. You can use `Arrays` class to sort your `exam` and `count` arrays instead of doing it on your own. – Tirath Oct 14 '14 at 10:37
  • How to do it ? Can u give me example for it ? I am quite new in java – Jen Oct 14 '14 at 11:13
  • possible duplicate of [Java: Sort an array](http://stackoverflow.com/questions/8938235/java-sort-an-array) – Tirath Oct 14 '14 at 13:08

1 Answers1

0

Here is how you can sort your arrays instead of doing it yourself using 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

Now, if you want to reverse it - use a for loop and read your array from last index to first index. I am sure you can make that.

Tirath
  • 2,294
  • 18
  • 27