Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Oct 2011
    Posts
    27
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Need help with Two-Dimensional array

    I added each row in a two-dimensional array and now I want to display this in decreasing order so How can I do that? .......any help would be greatly appreciated.

    int total;
    for(int row = 0; row < hours.length; row++)
    {
    total = 0;

    for(int col = 0; col < hours[row].length; col++)
    {
    total += hours[row][col];
    }

    System.out.println("Total of row " + row + " is " + total);

    }


    Here is the Output


    Total of row 0 is 28
    Total of row 1 is 51
    Total of row 2 is 47
    Total of row 3 is 30
    Total of row 4 is 40
    Total of row 5 is 45
    Total of row 6 is 47

  • #2
    New Coder
    Join Date
    Apr 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts
    You can simply use an array list to collect the various hourly values per row in the same loop, then you would simply just use java's native Collections and Comparator utilities.
    The Comparator would be used to define the sorting order whilst Collections can be used to sort the elements of an ArrayList.



    This is how you accomplish descending order list:
    PHP Code:
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;

    public class 
    sort 
    {
        public static 
    void main String [ ] args )
        {
            
    //create array list to collect hourly values per row
            
    ArrayList data = new ArrayList ( );
            
    //you would add hourly values per row here
            
    data.add 28 );
            
    data.add 51 );
            
    data.add 47 );
            
    data.add 30 );        
            
    data.add 40 );
            
    data.add 45 );
            
    data.add 47 );
            
    //use comparator to describe the sorting order
            
    Comparator comparator Collections.reverseOrder ( );
            
    //sort the array list, as defined by the comparator above
            
    Collections.sort data comparator );
            
    //display the contents of the array list 
            
    for ( int datum 0datum data.size ( ); datum ++ )
                
    System.out.println data.get datum ) );
        }

    Last edited by Bushman; 05-07-2012 at 02:35 AM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •