我刚刚开始在大学学习Java这个学期,虽然我可以做一些更基本的事情,但我可以通过编写简单的程序来工作,但我在编写这个程序时遇到了障碍。我还没有学过树(似乎是一个常见的修复),我需要帮助整理东西和创建新文件。
我的文件,Players& Score.txt包含以下内容:
布鲁斯127
Elayna 144
Lisa 153
马库斯188
Amber 133
Ryan 149
Dorian 099
Joel 175
Jenna 101
所以基本上我需要根据名称顺序在一个文件中对此列表进行排序,然后根据分数进行排序。到目前为止,我的代码看起来像这样。
import java.io.*;
import java.util.*;
/**
* Bruce P., November 14, 2013, CSC 131
* This program uses a file consisting of members of a bowling league. Each line has one name and the average score of the player.
* The program reads the file and then creates two new files in which one is sorted by alphabetical order of the player's name
* and the other is sorted in numerical order based on the player's score.
*
*/
public class MembersAndScores
{
public static void main(String[] args) throws IOException
{
File inputFile = new File("Players&Score.txt");
if (!inputFile.exists())
{
System.out.println("File Players&Score.txt was not found.");
System.exit(0);
}
Scanner input = new Scanner(inputFile);
String line;
File scoreSort = new File("SortedByName.txt");
PrintWriter writer = new PrintWriter(scoreSort);
}
}
我可能搞砸了这个,或者我看起来真的很蠢,寻求帮助。我只是不明白这一节以及如何做到这一点。任何帮助表示赞赏。
答案 0 :(得分:0)
这将根据名称排序。我很快就会添加分数代码。
import java.io.*;
import java.util.*;
/**
* Bruce P., November 14, 2013, CSC 131
* This program uses a file consisting of members of a bowling league. Each line has one name and the average score of the player.
* The program reads the file and then creates two new files in which one is sorted by alphabetical order of the player's name
* and the other is sorted in numerical order based on the player's score.
*
*/
public class MembersAndScores
{
public static void main(String[] args) throws IOException
{
try {
File inputFile = new File("Players&Score.txt");
if (!inputFile.exists())
{
System.out.println("File Players&Score.txt was not found.");
System.exit(0);
}
BufferedReader input=new BufferedReader(new FileReader(inputFile));
String line;
List<String> stl=new LinkedList();
while(true){
line=input.readLine();
if(line!=null&&line.length()>1)
stl.add(line);
if(line==null)
break;
}
data=new String[stl.size()];
for (int i=0;i<stl.size();i++) {
data[i]=stl.get(i);
}
Arrays.sort(data);
for (String string : data) {
System.out.println(string);
}
File scoreSort = new File("SortedByName.txt");
PrintWriter writer = new PrintWriter(scoreSort);
for (String string : data) {
writer.write(string+"\n");
}
writer.close();
} catch (Exception ex) {
Logger.getLogger(MembersAndScores.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
您可以获得Arrays.sort()here
的更多详细信息