Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 05-07-2012, 12:33 AM   PM User | #1
sabi
New Coder

 
Join Date: Oct 2011
Posts: 27
Thanks: 2
Thanked 0 Times in 0 Posts
sabi is an unknown quantity at this point
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
sabi is offline   Reply With Quote
Old 05-07-2012, 01:31 AM   PM User | #2
Bushman
New Coder

 
Join Date: Apr 2012
Posts: 12
Thanks: 0
Thanked 0 Times in 0 Posts
Bushman is an unknown quantity at this point
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 01:35 AM..
Bushman is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 07:07 PM.


Advertisement
Log in to turn off these ads.