简体   繁体   English

来自文本文件的Java排序行

[英]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. 我需要从文本文件中读取播放器,然后根据用户的选择输出排名前3、5或10的播放器。 Format of data in text file is: 文本文件中的数据格式为:

  • Name, date, correct answerws, points 名称,日期,正确答案,分数
  • John, 21.8.2016, 4/5, 80 约翰,21.8.2016,4/5,80
  • Edy, 21.8.2016, 5/5, 100 埃迪,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. 我需要按点对它们进行排序,然后按照我已经写好的输出3,5或10个最佳球员。

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? 如何按玩家点对文本文件中的这些行进行排序?

Use the array niz to recreate instances of the player class.. 使用数组niz重新创建播放器类的实例。

(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 然后从每一行创建一个播放器,并将其添加到java.util.list

ther sort them with a given criteria... correctAnswers or totalPoints 疗法与给定的标准...... correctAnswerstotalPoints对它们进行排序

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 之后,子列表可以为您提供所需的球员

ie

myPlayers.subList(0, 2);

will give the 1st 3 players... 将给第1名3名玩家...

where foo is an instance or an anonymous comparator implementor... 其中foo是实例或匿名比较器实现者...

I highly recommend that you approach this using BufferedReader rather than having three scanners. 我强烈建议您使用BufferedReader而不是使用三台扫描仪。 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. 使用这种方法,您可以使用", ""\\n"作为分隔符或其他所需内容逐行或逐段读取。

How about old good Stream API? 旧的优质Stream API怎么样?

Customize sortingKeyIndex, separator, neededLines to fit special needs. 自定义sortingKeyIndex, separator, neededLines以适应特殊需要。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM