8 Replies - 25963 Views - Last Post: 31 March 2012 - 11:58 AM Rate Topic: -----

#1 lytwynk   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 22-November 11

How do I sort an ArrayList of people alphabetically?

Posted 30 March 2012 - 08:26 PM

Hello, I am writing a program that reads in a file where the first line contains a persons name, the second line contains int value for sales and a float value for expenses. The program puts each persons information into an array list. The total sales and total expenses are calculated and each persons percentage of sales and percentage of expenses is printed in a table. The thing I am having trouble with is sorting the list alphabetically... Here is a bit of the file to read in...

Smith Kevin
80475 3966.27
Medina Norelis
71040 5677.21
Bailey Van
28305 11276.65

here is my main program...
import java.util.*;
import java.io.*;

public class TestSalesAndExpenses
{
	public static Scanner scan;
	public static void main(String[] args) throws IOException
	{
  		// Create an ArrayList called stats containing information concerning
		// SalesAndExpenses. 	
		ArrayList<SalesAndExpenses> list = new ArrayList<SalesAndExpenses>();
      SalesAndExpenses salesperson;
      // Read in a file and assign its contents to scan.    
		scan = new Scanner(new FileReader("sales"));
  		    
		String name;			// Declare string variable name.
		int sales;				// Declare int variable sales.
		float expenses;		// Declare float variable expenses.
		float line;				// Declare float variable line.
      
		// While there is information to read from the file,
		// assign the first line to name, the next integer
		// value to sales, and the final float value to expenses.
		while(scan.hasNext())
		{
         name = scan.nextLine();
         sales = Integer.parseInt(scan.next());
         expenses = new Float(scan.nextLine());
			// Create an instance of class SalesAndExpenses called salesperson
			// and assign name, sales, and expenses to it. Add each salesperson
			// to the ArrayList stats.
			salesperson = new SalesAndExpenses(name, sales, expenses);
         list.add(salesperson);
		}
      // Close scan.    
		scan.close();
		
		/******Need to sort the list of employees in alphabetical order******/  
		
		// For loop calculates the total sales of all the employees.
		int totalSales=0;
		for(int h=0; h<list.size(); h++)
		{
			totalSales = totalSales + list.get(h).getSales();
		}
      
		// For loop calculates the total expenses of all the employees.
		float totalExpenses=0;
		for(int h=0; h<list.size(); h++)
		{
			totalExpenses = totalExpenses + list.get(h).getExpenses();
		}
		
		// Title and headings for the table containing the employees
		// and their percentages of sales and expenses.
      System.out.println("*** List of Sales and Expenses ***");
		System.out.println("\nTotal Sales: $" + totalSales + "	" 
								 + " Total Expenses: $" + totalExpenses);
		System.out.println("\nName of Person" + "          " + "Percentage of Total Sales" 
								 + "       " + "Percentage of Total Expenses");           
		
		// Print the name, percent of sales and percent of expenses for each employee. 
		for(int j=0; j<list.size(); j++)
		{  	
			System.out.print("\n" + list.get(j).getName() + "\t\t" 
			+ (float)Math.round((float)list.get(j).getSales()/totalSales*10000)/100 + "%"  
			+ "\t\t\t\t" + (float)Math.round(list.get(j).getExpenses()/totalExpenses*10000)/100 + "%");
		}
	}
}


and my method program...
 
 public class SalesAndExpenses 
 {
	  private String name;
	  private int sales;
	  private float expenses;
     
     public SalesAndExpenses(String newName, int newSales, float newExpenses) 
	  {
         name = newName;
         sales = newSales;
         expenses = newExpenses;
	  }
     
     public String getName() 
	  {
         return name;
     }
     
     public int getSales() 
	  {
         return sales;
     }
     
     public float getExpenses() 
	  {
         return expenses;
     }
     
     public String toString() 
	  {
         return "\nName: " + this.getName() + "\tSales: " + this.getSales() + "\tExpenses: " +
                this.getExpenses(); 
     }
}

If you have any pointers I would really appreciate it!

Is This A Good Question/Topic? 0
  • +

Replies To: How do I sort an ArrayList of people alphabetically?

#2 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8379
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: How do I sort an ArrayList of people alphabetically?

Posted 30 March 2012 - 09:22 PM

If your class implements Comparable you can:
- use Collections.sort(arrayList);
- convert your ArrayList into an array and use Arrays.sort() to sort it

import java.util.*;

public class NameAndMoney implements Comparable<NameAndMoney> {
	
	String name;
	double money;
	
	
	NameAndMoney(String name, double money) {
		this.name = name;
		this.money = money;
	}
	public int compareTo(NameAndMoney other) {
       return name.compareTo(other.name);
	}
	public String toString() {
		return String.format("%10s %5f", name, money);
	}
	
	public static void main(String[] args) {
		ArrayList<NameAndMoney> al = new ArrayList<NameAndMoney>();
		al.add(new NameAndMoney("kkk", 123.4));
		al.add(new NameAndMoney("zzzzz", 456.7));
		al.add(new NameAndMoney("a", 9.0));
		NameAndMoney[] array = new NameAndMoney[al.size()];
		Arrays.sort(al.toArray(array));
		for(NameAndMoney x : array)
			System.out.println(x);
	}
}


This post has been edited by pbl: 04 April 2012 - 02:01 PM

Was This Post Helpful? 0
  • +
  • -

#3 lytwynk   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 22-November 11

Re: How do I sort an ArrayList of people alphabetically?

Posted 31 March 2012 - 11:06 AM

Ok I have tried converting my ArrayList to an array for now... I haven't started to sort the array but when I run the program this is thrown...

----jGRASP exec: java TestSalesAndExpenses

Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.ArrayList.toArray(ArrayList.java:306)
at TestSalesAndExpenses.main(TestSalesAndExpenses.java:41)

----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.

Here is my revised code, and again any help you could give is much appreciated:

import java.util.*;
import java.io.*;

public class TestSalesAndExpenses  
{
	public static Scanner inFile;
	public static void main(String[] args) throws IOException
	{
  		// Create an ArrayList called stats containing information concerning
		// SalesAndExpenses. 	
		ArrayList<SalesAndExpenses> list = new ArrayList<SalesAndExpenses>();
      SalesAndExpenses salesperson;
      // Read in a file and assign its contents to scan.    
		inFile = new Scanner(new FileReader("sales"));
  		    
		String name;			// Declare string variable name.
		int sales;				// Declare int variable sales.
		float expenses;		// Declare float variable expenses.
		float line;				// Declare float variable line.
      
		// While there is information to read from the file,
		// assign the first line to name, the next integer
		// value to sales, and the final float value to expenses.
		while(inFile.hasNext())
		{
         name = inFile.nextLine();
         sales = Integer.parseInt(inFile.next());
         expenses = new Float(inFile.nextLine());
			// Create an instance of class SalesAndExpenses called salesperson
			// and assign name, sales, and expenses to it. Add each salesperson
			// to the ArrayList stats.
			salesperson = new SalesAndExpenses(name, sales, expenses);
         list.add(salesperson);
		}
      // Close scan.    
		inFile.close();
		
		/******Need to sort the list of employees in alphabetical order******/ 
		
		String[] list2 = new String[list.size()];
		list.toArray(list2);
		 
		
		//******************************************************************** 
		
		// For loop calculates the total sales of all the employees.
		int totalSales=0;
		for(int h=0; h<list.size(); h++)
		{
			totalSales = totalSales + list.get(h).getSales();
		}
      
		// For loop calculates the total expenses of all the employees.
		float totalExpenses=0;
		for(int h=0; h<list.size(); h++)
		{
			totalExpenses = totalExpenses + list.get(h).getExpenses();
		}
		
		// Title and headings for the table containing the employees
		// and their percentages of sales and expenses.
      System.out.println("*** List of Sales and Expenses ***");
		System.out.println("\nTotal Sales: $" + totalSales + "	" 
								 + " Total Expenses: $" + totalExpenses);
		System.out.println("\nName of Person" + "          " + "Percentage of Total Sales" 
								 + "       " + "Percentage of Total Expenses");           
		
		// Print the name, percent of sales and percent of expenses for each employee. 
		for(int j=0; j<list.size(); j++)
		{  	
			System.out.print("\n" + list.get(j).getName() + "\t\t" 
			+ (float)Math.round((float)list.get(j).getSales()/totalSales*10000)/100 + "%"  
			+ "\t\t\t\t" + (float)Math.round(list.get(j).getExpenses()/totalExpenses*10000)/100 + "%");
		}
	}
}

Was This Post Helpful? 0
  • +
  • -

#4 Ryano121   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • Posts: 3,289
  • Joined: 30-January 11

Re: How do I sort an ArrayList of people alphabetically?

Posted 31 March 2012 - 11:09 AM

'list' is an ArrayList of SalesAndExpenses objects, yet the array that you want to store it in- 'list2' - is an array of Strings.
Was This Post Helpful? 0
  • +
  • -

#5 lytwynk   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 22-November 11

Re: How do I sort an ArrayList of people alphabetically?

Posted 31 March 2012 - 11:21 AM

Ok so I changed the code to this...
[code] /******Need to sort the list of employees in alphabetical order******/

SalesAndExpenses[] list2 = new SalesAndExpenses[list.size()];
list.toArray(list2);

//********************************************************************[code]

It compiles and runs however when I add "list2.sort();" afterwards this error is thrown...

----jGRASP exec: javac -g TestSalesAndExpenses.java

TestSalesAndExpenses.java:42: cannot find symbol
symbol : method sort()
location: class SalesAndExpenses[]
list2.sort();
^
1 error

----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Was This Post Helpful? 0
  • +
  • -

#6 Ryano121   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • Posts: 3,289
  • Joined: 30-January 11

Re: How do I sort an ArrayList of people alphabetically?

Posted 31 March 2012 - 11:25 AM

You have to invoke the sort method via the Arrays class -

Arrays.sort(list2);

Was This Post Helpful? 0
  • +
  • -

#7 lytwynk   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 22-November 11

Re: How do I sort an ArrayList of people alphabetically?

Posted 31 March 2012 - 11:33 AM

Ok, did that then tried to print the sorted list just to see if it worked correctly...
		/******Need to sort the list of employees in alphabetical order******/ 
		
		SalesAndExpenses[] list2 = new SalesAndExpenses[list.size()];
		list.toArray(list2);
		Arrays.sort(list2);
		System.out.println(list2);
		
		//********************************************************************


But it printed this...(the bold print is where the sorted list should be).

----jGRASP exec: java TestSalesAndExpenses

[LSalesAndExpenses;@158b649
*** List of Sales and Expenses ***

Total Sales: $555000 Total Expenses: $77770.01

Name of Person Percentage of Total Sales Percentage of Total Expenses

Smith Kevin 14.5% 5.1%
Medina Norelis 12.8% 7.3%
Bailey Van 5.1% 14.5%
Keepes Karen 10.6% 9.5%
Keepes Ron 11.7% 8.4%
Carey Harry 6.2% 13.9%
Hairy Mata 7.3% 12.8%
Hurry Mata 9.5% 10.6%
Hurry Caine 8.4% 11.7%
Petz Edz 13.9% 6.2%
----jGRASP: operation complete.
Was This Post Helpful? 0
  • +
  • -

#8 Ryano121   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1461
  • View blog
  • Posts: 3,289
  • Joined: 30-January 11

Re: How do I sort an ArrayList of people alphabetically?

Posted 31 March 2012 - 11:36 AM

You are just printing out the array variable and not the actual contents of the array.

You need to loop through each element and print each out.
Was This Post Helpful? 0
  • +
  • -

#9 lytwynk   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 33
  • Joined: 22-November 11

Re: How do I sort an ArrayList of people alphabetically?

Posted 31 March 2012 - 11:58 AM

Bingo! Thanks for all your help!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1