1
import java.io.File;
import java.util.Scanner;

public class MainClass {

    public static Winner [] listOfWinners;

    public static void loadFromFile()
    {
        try{
            //Create instance of Scanner and provide instance of File pointing to the txt file
            Scanner input = new Scanner(new File("WorldSeriesWinners.txt"));

            //Get the number of teams
            int years = input.nextInt();
            input.nextLine();//move to the next line

            //Create the array
            listOfWinners = new Winner[years];

            //for every year in the text file
            for(int index = 0; index<years; index++)
            {
                //Get the year
                int year = input.nextInt();
                input.skip("    ");
                //Get the team
                String team = input.nextLine();

                //Create an instance of Winner and add it to the next spot in the array
                listOfWinners[index] = new Winner(team,year);
            }
        }catch(Exception e)
        {
            System.out.println("Something went wrong when loading the file!");
            System.out.println(e.toString());
            System.exit(0);
        }
    }

    public static void sortByTeamName()
    {

    }

I've been searching online for a few hours but cannot figure out a way to properly sort the array alphabetically

4
  • 3
    Make it into list and just call Collections.sort()? or just simply do Arrays.sort() Commented Dec 11, 2016 at 21:05
  • I cannot use Array.sort because the array contains both numbers and letters Commented Dec 11, 2016 at 21:12
  • You could use a different data structure that would sort the items as you insert them Commented Dec 11, 2016 at 21:12
  • 1
    Yes, you can use that method. You give it a Comparator, as the below answer shows. Commented Dec 11, 2016 at 21:13

1 Answer 1

1

You could use the following snippet for sorting by Team name, by taking advantage of the comparator feature of the Arrays.sort(arr[],comparator)

Arrays.sort(listOfWinners, new Comparator<Winner>() {

            @Override
            public int compare(Winner o1, Winner o2) {

                return o1.team.compareTo(o2.team);
            }
        });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.