【发布时间】:2018-06-29 10:24:45
【问题描述】:
我有一个文本文件,其中包含以下文本:
输入.txt:
name s1 s2 s3 s4
Jack 2 4 6 5
Alex 3 5 5 5
Brian 6 6 4 5
现在布莱恩的最高平均值是:5.2;亚历克斯:4.5;杰克:4.25。 我的任务是获取每个人的平均数,然后按平均分数升序对人进行排序,然后使用排序后的值创建一个新的文本文件。
以上示例在新文本文件中必须如下所示。
输出.txt:
name s1 s2 s3 s4
Brian 6 6 4 5
Alex 3 5 5 5
Jack 2 4 6 5
到目前为止,我想出了 2 个解决方案,没有一个可以完成任务。
第一个是:
public class Sort {
public static void main(String[] args) throws IOException {
int sortKeyIndex = 0;
Path inputFile = Paths.get("C:\\Users\\Desktop\\sample.txt");
Path outputFile = Paths.get("C:\\Users\\Desktop\\new-sample.txt");
String separator = " ";
Stream<CharSequence> sortedLines =
Files.lines(inputFile)
.skip(1)
.map(sorting -> sorting.split(separator))
.sorted(Comparator.comparing(sorting -> sorting[sortKeyIndex]))
.map(sorting -> String.join(separator, sorting));
Files.write(outputFile, sortedLines::iterator, StandardOpenOption.CREATE);
}
}
第二个是:
public class SortTestSecond {
private static BufferedReader theReader;
public static void main(String[] args) throws IOException {
try {
theReader = new BufferedReader(new FileReader("C:\\Users\\Desktop\\test2.txt"));
theReader.readLine();
String currLine = null;
while((currLine = theReader.readLine()) != null) {
System.out.println(currLine);
StringTokenizer strTok = new StringTokenizer(currLine, " ");
int theCount=strTok.countTokens();
int theArray[]=new int[theCount];
int i = 0;
while(strTok.hasMoreTokens() && i != theCount) {
theArray[i]=Integer.valueOf(strTok.nextToken());
i = i + 1;
}
int theSum = 0;
for(int j =0;j < theArray.length; j++) {
theSum = theSum + theArray[j];
}
float average = (float) theSum / theArray.length;
System.out.println("Average: " + average);
}
} catch(IOException err) {
err.printStackTrace();
} finally {
theReader.close();
}
}
}
【问题讨论】:
-
您可以编辑您的帖子以添加运行每个解决方案的结果吗?谢谢
-
错误的缩进使代码不可读。请重新格式化您的代码。
-
@JohnM 好吧,我可以按字母顺序对它们进行排序,并且可以按第一个数字对它们进行排序,但是我不知道如何找到每行数字的平均值,然后像在我提供的 Output.txt。
-
@vanje 抱歉,我不知道是不是我做的,因为我是新来的……
标签: java arrays sorting text-files java-stream