alonso05
alonso05

Reputation: 135

Java sort lines from text file

I need to read players from text file, and then output top 3, 5 or 10 players depends on users choice. Format of data in text file is:

I need to sort them by points and then output best 3,5 or 10 players as i already write.

Here is what i done so far:

public static void topPlayers(){

    File f=new File("results.txt");
    Scanner scf=new Scanner(f);
    Scanner sc=new Scanner(System.in);

    Scanner sc2=new Scanner(f);

    while(sc2.hasNextLine()){
      String p1=scf.nextLine();
      String[] niz=p1.split(", ");
    }
    sc2.close();

    System.out.println("Choose an option: ");
    System.out.println("1. Top 3 players"); 
    System.out.println("2. Top 5 players");
    System.out.println("3. Top 10 players");
    int op=sc.nextInt();

    if(op==1){
       System.out.println("Top 3 players: ");
       for(int i=0; i<3; i++){
         //System.out.println(....);
       }
    }
    else if(op==2){
      System.out.println("Top 5 players: ");
      for(int i=0; i<5; i++){
         //System.out.println(....);
       }
    }
    else if(op==3){
      System.out.println("Top 10 players: ");
      for(int i=0; i<10; i++){
         //System.out.println(....);
       }
    }
    else{
       System.out.println("Wrong option!");
    }
  }

How to sort this lines from text file by players point?

Upvotes: 0

Views: 1493

Answers (3)

diziaq
diziaq

Reputation: 7795

How about old good Stream API?

Customize sortingKeyIndex, separator, neededLines to fit special needs.

import java.nio.file.*;
import java.util.Comparator;
import java.util.stream.Stream;

public class FileSortWithStreams {

    public static void main(String[] args) throws Exception {
        Path initialFile = Paths.get("files/initial.txt");
        Path sortedFile = Paths.get("files/sorted.txt");

        int sortingKeyIndex = 3;
        String separator = ", ";
        int neededLines = 5;


        Comparator<String[]> reversedPointsComparator =
                Comparator
                        .<String[], Integer>comparing(s -> extractAsInt(s, sortingKeyIndex))
                        .reversed();

        Stream<CharSequence> sortedLines =
                Files.lines(initialFile)
                     .map(s -> s.split(separator))
                     .sorted(reversedPointsComparator)
                     .limit(neededLines)
                     .map(s -> String.join(separator, s));

        Files.write(sortedFile, sortedLines::iterator, StandardOpenOption.CREATE);
    }

    static int extractAsInt(String[] items, int index) {
        return Integer.parseInt(items[index]);
    }
}

Upvotes: 0

g_haxor
g_haxor

Reputation: 29

I highly recommend that you approach this using BufferedReader rather than having three scanners. This snippet will cause you infinite headaches:

File f=new File("results.txt");
Scanner scf=new Scanner(f);
Scanner sc=new Scanner(System.in);

Scanner sc2=new Scanner(f);

Instead, use something resembling this:

File f = new File("results.txt");
FileReader fileIn = new FileReader(f);
BufferedReader reader = new BufferedReader(fileIn);

Using this approach, you can read line by line or segment by segment using ", " and "\n" as delimeters or whatever else you need.

Upvotes: 1

Use the array niz to recreate instances of the player class..

(yes, you will need if not already, to create a player class)

then from every line create a player and add it to a java.util.list

ther sort them with a given criteria... correctAnswers or totalPoints

up to your needs.

Example:

 List<Player> myPlayers = new ArrayList<>();
 while(sc2.hasNextLine()){
      String p1=scf.nextLine();
      String[] niz=p1.split(", ");
      myPlayers.add(new Player(niz));
    }
 

Collections.sort(myPlayers, new Comparator<Player>() {
    @Override
    public int compare(Player o1, Player o2) {

    return Integer.compare(o1.getTotalPoints(), o2.getTotalPoints());
    }
});

after this, a sublist can give you the players you need

i.e

myPlayers.subList(0, 2);

will give the 1st 3 players...

where foo is an instance or an anonymous comparator implementor...

Upvotes: 0

Related Questions