我正在使用eclipse在java中编写一个简单的游戏猜测。现在我想按升序打印出细节。我在这个论坛上尝试了很多方法,但无法解决。这就是我需要你帮助的原因。
我的代码如下:
File f = new File ("scores.txt");
// name of the folder created at the root of the project
String ligne;
try
{
PrintWriter pw = new PrintWriter (new BufferedWriter (new FileWriter (f, true)));
if (numberOfTries==1){
pw.println (numberOfTries + " try by " + str ) ;
}
else if (numberOfTries!=1){
pw.println (numberOfTries + " tries by " + str ) ;
}
// pw.println (numberOfTries) ;
pw.close ();
// this line MUST be written.
}
catch (IOException exception) {
System.out.println ("Error while writing data:" + exception.getMessage());
}
BufferedReader ficTexte;
// to read from a folder text.
try {
ficTexte = new BufferedReader (new FileReader(f));
do {
ligne= ficTexte.readLine();
if (ligne !=null)
// if the line is not empty.
System.out.println(ligne);
} while (ligne !=null);
ficTexte.close();
System.out.println("\n");
}
// Show message in case of errors.
catch (FileNotFoundException e) {
System.out.println (e.getMessage());
}
catch (IOException e) {
System.out.println (e.getMessage());
}
}
假设我有
3 tries by Vibe
2 tries by NoNo
10 tries by Caroline
7 tries by Mata
10 tries by Lionel
我希望它安排如下:
2 tries by NoNo
3 tries by Vibe
7 tries by Mata
10 tries by Caroline
10 tries by Lionel
怎么可能呢?
答案 0 :(得分:0)
试试这个:
private static final Comparator<String> CMP = new Comparator<String>()
{
@Override
public int compare(final String a, final String b)
{
final int inta = Integer.parseInt(a.split("\\s+")[0]);
final int intb = Integer.parseInt(b.split("\\s+")[0]);
return Integer.compare(inta, intb);
}
}
然后,在代码后面:
final Path file = Paths.get("scores.txt");
final List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
Collections.sort(lines, CMP);
for (final String line: lines)
System.out.println(line);
(类似地,您应该使用Files.newBufferedWriter()
为您的文件获取Writer
)
答案 1 :(得分:0)
基本解决方案: