w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Java - Eclipse - Take names and numbers from a file, sort alphabetically into a new file, sort numerically into a new file

This will sort according to the names . I will add the code for scores soon .

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

/**
 * Bruce P., November 14, 2013, CSC 131
 * This program uses a file consisting of members of a bowling league. Each
line has one name and the average score of the player.
 * The program reads the file and then creates two new files in which one
is sorted by alphabetical order of the player's name
 * and the other is sorted in numerical order based on the player's score.
 *
 */

public class MembersAndScores 
{

    public static void main(String[] args) throws IOException
    {

        try {
            File inputFile = new File("Players&Score.txt");
            if (!inputFile.exists())
            {
                System.out.println("File Players&Score.txt was not
found.");
                System.exit(0);
            }

            BufferedReader input=new BufferedReader(new
FileReader(inputFile));
            String line;
            List<String> stl=new LinkedList();
            while(true){
                line=input.readLine();
                if(line!=null&&line.length()>1)
                stl.add(line);
                if(line==null)
                    break;
            }

            data=new String[stl.size()];
            for (int i=0;i<stl.size();i++) {
                data[i]=stl.get(i);
            }

            Arrays.sort(data);
            for (String string : data) {
                System.out.println(string);
            }

            File scoreSort = new File("SortedByName.txt");
            PrintWriter writer = new PrintWriter(scoreSort);
            for (String string : data) {
                writer.write(string+"
");
            }

            writer.close();

        } catch (Exception ex) {
           
Logger.getLogger(MembersAndScores.class.getName()).log(Level.SEVERE, null,
ex);
        }

    }

}

You can get more details of Arrays.sort() here





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.