user3188039
user3188039

Reputation: 33

sort the output by sum in java

I wrote a program that reads from a file which has hundreds sets of numbers (each set has 20 numbers). the point of the program is to produce the sum of each set, # of even, # of odd.

here is my code:

public static void main(String args[])
{


    System.out.println(String.format("%-10s%-10s%-10s", "sum", "even", "odd"));     
    try
    {

          FileInputStream fstream = new FileInputStream("data.txt");
          DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));
          String strLine;
          while ((strLine = br.readLine()) != null)   {
              String[] numberStrs = strLine.split("\t");
              int[] numbers = new int[numberStrs.length];

              for(int i = 0;i < numberStrs.length;i++)
              {
                  numbers[i] = Integer.parseInt(numberStrs[i]);
                  //System.out.println(numbers[i]);
              }
              int sumTotal = sum(numbers);
              for (int j =0; j<numbers.length;j++)
              {
                  if (isEven(numbers[j]) == true)
                  {
                      evenCounter++;
                  }
                  else
                  {
                      oddCounter++;
                  }

              }
              System.out.println(String.format("%-10s%-10s%-10s", sumTotal, evenCounter, oddCounter + "\n");
              }
              in.close();

    }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
          }

          }

now, the output is hundreds of rows and 3 columns (sum, even, odd). my question is, how to sort the output by the sum (the even and odd is linked to the sum).

for example:

sum   odd   even
404   4     10
120   21     5

what I want is to sort the sum and have:

sum   odd   even
120   21    5
404   4     10

Upvotes: 0

Views: 1311

Answers (3)

Samurai Girl
Samurai Girl

Reputation: 998

In order to sort, you will have to store the calculated data somewhere instead of printing it on the fly. You can store them in a 3 x N array, write a Comparator which compares only one dimension of it and then sort the array with your comparator.

for example:

int[][] arr = new int[N][3];

// populate arr with data here

Arrays.sort(arr, new Comparator<int[]>(){
    @Override
    public int compare(int[] o1, int[] o2) {    
        return o1[0] - o2[0];
    }                     
});

Upvotes: 0

Hugo Sousa
Hugo Sousa

Reputation: 1936

You could have a Set class, where you save the sum, number of odds and number of evens. You save an array of Set's and then you can sort it by sum (you can write a simple Comparator) and then display it.

Upvotes: 0

Glenn Lane
Glenn Lane

Reputation: 4030

Your data needs to be stored so it can be sorted later. The best way to do this is to design a class that is responsible for:

  • Storing the data
  • Sorting
  • Maintaining a tally of sum and event & odd counts
  • Representing itself as a string

This moves some complexity out of your code. Here is an example.

The Sum class:

public class Sum implements Comparable<Sum>
{
    private int sumTotal;
    private int evenCount;
    private int oddCount;

    public void addNumber(int n)
    {
        sumTotal += n;
        if ((n & 0x1) == 0x1)
        {
            oddCount++;
        }
        else
        {
            evenCount++;
        }
    }

    @Override
    public int compareTo(Sum other)
    {
        return Integer.compare(sumTotal, other.sumTotal);
    }

    @Override
    public String toString()
    {
        return String.format("%-10s%-10s%-10s", sumTotal, evenCount, oddCount);
    }

}

And your revised code:

public static void main(String[] args)
{
    System.out.println(String.format("%-10s%-10s%-10s", "sum", "even",
            "odd"));
    try
    {
        // The maintained sum list
        List<Sum> sumList = new ArrayList<Sum>();
        InputStream fstream = new FileInputStream("data.txt");
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        while ((strLine = br.readLine()) != null)
        {
            // Prepare to insert a new sum object
            Sum newSum = new Sum();
            String[] numberStrs = strLine.split("\t");
            for (String numberStr : numberStrs)
            {
                // The sum object manages its own tallies
                newSum.addNumber(Integer.parseInt(numberStr));
            }
            // Append the new object to the list
            sumList.add(newSum);
        }
        in.close();
        // Sort the list
        Collections.sort(sumList);

        // Print the list
        for (Sum sum : sumList)
        {
            /*
             * The sum object is responsible for generating its own string 
             * representation
             */
            System.out.println(sum);

        }
    }
    catch (Exception e)
    {
        // Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

}

Upvotes: 1

Related Questions