我正在尝试创建一个读取文本文件的类,每行具有相同的格式,“#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();
}
}
非常感谢任何反馈!
答案 0 :(得分:3)
Arrays.sort
期待T[]
但您提供的ArrayList
不是数组,它是一个在内部使用数组来保存元素的列表。
使用Collections.sort
代替,或者从Java 8开始,您可以使用yourList.sort(comparator)
。
BTW split
方法使用正则表达式(正则表达式)作为参数,其中)
是正则表达式special characters之一。如果您想将)
视为文字,则需要将其转义(Escape ( in regular expression处的更多信息)
因此,您可以使用aScore.split(") ");
aScore.split("\\) ");