【发布时间】:2014-02-23 21:57:13
【问题描述】:
所以我在这里有这段代码,它获取一个文件并将其放入一个数组中。我现在需要做的是将第二列中的整数从大到小排序。这是我的代码,底部有一个指向数据文件的链接。我知道有排序算法,但我不知道如何实现它们。
import java.util.*;
import java.io.*;
public class sorter{
public static int id = 0;
public static int score = 0;
public static void main(String args[]){
Scanner inFile = null;
try {
inFile = new Scanner (new File ("sorter.txt"));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.exit(0);
}
while (inFile.hasNextLine()){
String str = inFile.nextLine();
String [] parts = str.split(" ");
String part1 = parts[0];
String part2 = parts[1];
id = Integer.parseInt(part1);
score = Integer.parseInt(part2);
System.out.println(part1 + " " +part2);
}
}
}
输出应该是这样的:
/*
ID Score
305 265
306 262
115 257
311 256
123 253
116 246
325 246
321 245
323 245
113 243
218 243
208 242
302 242
112 239
104 239
110 238
223 230
213 229
207 228
203 224
222 223
*/
【问题讨论】:
-
通常情况下,您不必实现它们。我会看一下Java Arrays API。我相信你可以想出一种对数组进行排序的方法。试着在纸上画出你将如何对一个小数组进行排序
-
@user3259415 你是按ID还是Score排序?
-
嗯,你应该先保存每个分数/id,排序然后打印
-
我认为更大的问题是保持 id 与适当的分数相匹配。
标签: java arrays file sorting integer