0

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:

  • Name, date, correct answerws, points
  • John, 21.8.2016, 4/5, 80
  • Edy, 21.8.2016, 5/5, 100

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?

2
  • how does the lines look like???? Commented Aug 21, 2016 at 16:23
  • NameOfPlayers, dateOfPlaying, correctAnswers, totalPoints its all in one line and now i need to sort them by totalPoints and the output 3,5 or 10 Commented Aug 21, 2016 at 16:25

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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...

4 Comments

Thanks for help, if i understand you this foo is criteria for sorting, and if that is correct how can i make it to sort by totalPoints
and after sorting how can i output specific number of players from this list, this is forst time that i work with list and that is why i have so much questions
listo alonso, see update... you need to use myPlayers.subList(0, n);
thank you, now i have problem with this constructor Player(i use the nyme of my class which is Kviz) but it throw error 3 errors found: Error: constructor Kviz in class Kviz cannot be applied to given types; required: no arguments found: java.lang.String[] reason: actual and formal argument lists differ in length Error: cannot find symbol symbol: method getTotalPoints() location: variable o1 of type Kviz Error: cannot find symbol symbol: method getTotalPoints() location: variable o2 of type Kviz
0

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]);
    }
}

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.