我有一個名爲亞軍類,它看起來是這樣的:Java - 如何使用bufferedReader和Scanner將數據讀入列表?
public class Runner
{
private static int nextNumber= 1;
private int number;
private String name;
private String ageGroup;
private int time;
public Runner()
{
super();
this.name = "";
this.ageGroup = "standard";
this.time = 0;
this.number = nextNumber++;
}
它還包括標準的getter和setter方法。 在另一個類中,我試圖編寫一個方法,用於從文本文件中讀取數據並將數據分配給列表。我的方法目前看起來是這樣的:
public void readInRunners()
{
String pathname = OUFileChooser.getFilename();
File aFile = new File(pathname);
Scanner bufferedScanner = null;
List<Runner> runners = new ArrayList<>();
try
{
String name;
int age;
String ageGroup;
Scanner lineScanner;
String currentLine;
bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
while (bufferedScanner.hasNextLine())
{
currentLine = bufferedScanner.nextLine();
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
name = lineScanner.next();
age = lineScanner.nextInt();
if(age < 18)
{
ageGroup = ("junior");
}
else if(age >= 55)
{
ageGroup = ("senior");
}
else if(age >= 18 && age < 55)
{
ageGroup = ("standard");
}
runners.add(new Runner(name, ageGroup));
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedScanner.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
我在這條線得到一個錯誤:
runners.add(new Runner(name, ageGroup));
我知道那是因爲不兼容的說法是沒有編制,但我不知道該如何否則這句話。
任何意見將不勝感激。
它誠實地看起來像你的問題不是從文件讀取。 –
只需要注意,你不需要'this.time = 0;','time'已經被初始化爲'0'(int變量的默認值)。 – Berger