2016-12-11 54 views
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() 
    { 

    } 

我一直在網上搜索了幾個小時,但不能想出一個辦法來排列的字母順序排序對象aplhabetically在Array

+3

成爲列表,只是調用'Collections.sort()'?或只是簡單地執行'Arrays.sort()' – 3kings

+0

我不能使用Array.sort,因爲數組包含數字和字母 –

+0

您可以使用不同的數據結構,在插入項目時對項目進行排序 –

回答

1

您可以使用下面的代碼片段通過團隊名稱排序正確排序,通過利用比較器功能的優勢Arrays.sort(arr[],comparator)

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

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

       return o1.team.compareTo(o2.team); 
      } 
     }); 
+0

謝謝!這很好用! –