我正在尝试创建一个读取文本文件的类,每行具有相同的格式,"#order(分数 - 名称"。我希望能够从文件中读取每一行并将其存储在数组中,然后按最高分对其进行排序。当它只是"#order(分数"时,我能够完成此操作,但是将字符串添加到混合物中会使事情变得复杂。错误是
Scoring.java:46: error: no suitable method found for sort(ArrayList<String>,<anonymous Comparator<String>>)
Arrays.sort(scores, new Comparator<String>(){
^
method Arrays.<T#1>sort(T#1[],Comparator<? super T#1>) is not applicable
(cannot infer type-variable(s) T#1
(argument mismatch; ArrayList<String> cannot be converted to T#1[]))
method Arrays.<T#2>sort(T#2[],int,int,Comparator<? super T#2>) is not applicable
(cannot infer type-variable(s) T#2
(actual and formal argument lists differ in length))
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>sort(T#1[],Comparator<? super T#1>)
T#2 extends Object declared in method <T#2>sort(T#2[],int,int,Comparator<? super T#2>)
文本文件为:
1) 10000 - Michael
2) 10000 - Jake
3) 10000 - Alex
类是:
import java.io.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Comparator;
public class Scoring
{
private ArrayList<String> scores = new ArrayList<String>();
public Scoring()
{
this(-1, "-1");
}
public Scoring(int newScore, String newName)
{
String highScoreFile = "scores.txt";
String line;
BufferedReader reader = null;
try
{
File file = new File(highScoreFile);
reader = new BufferedReader(new FileReader(file));
}
catch (FileNotFoundException fnfe)
{
fnfe.printStackTrace();
}
finally
{
try
{
while ((line = reader.readLine()) != null)
{
String aScore = line;
String segments[] = aScore.split(") ");
aScore = segments[segments.length - 1];
scores.add(aScore);
}
if (newScore != -1 && !newName.equals("-1"));
{
scores.add(newScore + " - " + newName);
}
System.out.println(Arrays.toString(scores.toArray()));
Arrays.sort(scores, new Comparator<String>(){
@Override
public int compare(String o1, String o2)
{
return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
}
});
BufferedWriter writer = null;
try
{
File file = new File(highScoreFile);
FileWriter fw = new FileWriter(file);
writer = new BufferedWriter(fw);
}
catch (FileNotFoundException fnfe)
{
fnfe.printStackTrace();
}
for (int i = 0; i < scores.size(); i++)
{
writer.write((i + 1) + ") ");
writer.write(scores.get(i) + "n");
}
System.out.println(Arrays.toString(scores.toArray()));
reader.close();
writer.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
public static void main(String[] args) {
Scoring score = new Scoring();
}
}
任何反馈将不胜感激!
Arrays.sort
期待T[]
但您提供的ArrayList
不是数组,它是一个在内部使用数组来保存元素的列表。
请改用Collections.sort
,或者从 Java 8 开始,您可以使用 yourList.sort(comparator)
.
顺便说一句,split
方法使用正则表达式(正则表达式(作为参数,其中)
是正则表达式特殊字符之一。如果要将)
视为文字,则需要对其进行转义(更多信息请参阅转义(正则表达式(
因此,您可以使用aScore.split("\) ");
而不是aScore.split(") ");