Results 1 to 2 of 2
  1. #1
    atac57 is offline Member
    Join Date
    Jan 2012
    Posts
    24
    Rep Power
    0

    Default Any ideas for sorting data in a file in descending order?

    I'm making a Battleship game and I'm adding a top scores file. The file being written to will contain information like this:
    ***Name: Bob ***Score: 5000
    ***Name: Tom ***Score: 2000
    ***Name: Alan ***Score: 8000

    ...and I want the program to print it out like this, in order.

    ***Name: Alan ***Score: 8000
    ***Name: Bob ***Score: 5000
    ***Name: Tom ***Score: 2000

    This code snippet prints out the file as it is without the scores, but the names are not in order based on the scores. Under that are the scores in the order I want them using the Collections class, thats the best I could do. Any ideas? Thanks.
    Java Code:
    ArrayList<Integer> list = new ArrayList<Integer>();	
    		try {
    			Scanner file = new Scanner(new File(filePath));
    			while (file.hasNext()) {
    				if (file.hasNextInt()){
    					list.add(file.nextInt());	 
    				}
    				else{
    					System.out.printf("%s %s\t\t%s\n", file.next(), file.next(), file.next());
    				}
    			}
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		}
    		
    		Collections.sort(list);
    		Collections.reverse(list);
    		for (Integer i : list)
    		System.out.printf("%d\n", i);

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,457
    Rep Power
    20

    Default Re: Any ideas for sorting data in a file in descending order?

    Don't use a List, use a SortedSet.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. Replies: 2
    Last Post: 11-13-2011, 06:17 PM
  2. Sorting in ascending and descending order
    By flpanthers1 in forum New To Java
    Replies: 10
    Last Post: 06-27-2011, 04:48 PM
  3. [SOLVED] Sorting array in descending order?
    By dan0 in forum New To Java
    Replies: 14
    Last Post: 04-16-2009, 01:19 AM
  4. Sorting in descending order
    By santanu in forum New To Java
    Replies: 6
    Last Post: 11-27-2008, 12:43 AM
  5. Display the data in Descending order
    By santanu in forum New To Java
    Replies: 2
    Last Post: 10-31-2008, 01:06 PM

Posting Permissions

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