![](/img/trans.png)
[英]Java - NullPointerException after initializing array and when testing array with class method
[英]Initializing an array using a method - Java
我有一個文本文件,其中包含n個運動員的名字,每個名字在新行中,並且運動員的人數在文本文件的第一行中寫為int。 到目前為止,我編寫的代碼將讀取文本文件,並使用掃描儀並創建一個包含所有數據(運動員名稱)的數組。 我想知道的是,是否有可能使用一種方法為每個運動員創建一個單獨的數組(我稍后將用分數/表現數據填充這些數組)。 在掃描文本文件之前,我無法初始化這些文件,因為尚不知道運動員的數量。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TextScanner {
private static void readFile(String fileName) {
try {
List<String> distance = new ArrayList<String>();
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
distance.add(scanner.next());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
readFile(args[0]);
}
}
Java的新手,對不起。 我環顧四周,似乎找不到任何信息。 謝謝
是的,這是可能的,但是Array
具有一定的局限性,因為它無法動態擴展和折疊
試試這個
創建一個具有要為運動員保留的屬性的集體Athelete
說
Class Athelete{
private String name;
private Integer age;
private String skill;
// then Getters and Setters for each of these
}
並創建一個地圖
Map<String,Athelete> // having `name` as Key and `athelete object` as value.
現在,從文件讀取並創建Athelete對象,並將其添加到Map
。
Person p=new Person();
p.setName=nameFromFile();
// also set further attributes
map.put(p.getName,p);
您可以創建Athlete
類:
class Athlete{
String name;
int score;
Athlete(String name){
this.name = name;
}
int getScore(){return score;}
void setScore(int score){ this.score = score}
}
並將“ Athlete
實例插入數組或“列表”中:
List<Athlete> distance = new ArrayList<>();
distance.add(new Athlete('Some name'));
UPD:如果您使用Java7,請考慮使用java.nio.file.Files
代替Scanner
讀取小文件。 我認為readAllLines方法對您有用。
由於Java是面向對象的語言,因此請考慮對象,在您的情況下,它似乎是運動員,成績和表現
public class Athlete {
String name;
List<Score> scores = new ArrayList<Score>();
List<Performance> performances = new ArrayList<Performance>();
}
public class Score {
String score
}
public class Performance {
int performnce
}
所以List<String> distance = new ArrayList<String>();
這將成為List<Athlete> Athletes = new ArrayList<Athlete>();
對於文件中的每個記錄,創建“運動員”對象並將名稱存儲在name
實例變量中。 當您獲得每個特定運動員的成績和表現時,就更新了上面已經創建的運動員對象。
更新資料
正如其他評論員所指出的那樣,使用Map
而不是List
是合適的。 例如, Map<String, Athlete> athletes = new HashMap<String, Athlete>();
這樣,以后在接收到樂譜和表現時進行更新變得更加容易。 同樣,得分和表現也列為一名運動員,它可以具有多個得分和表現。
您可以先將所有數據(運動員名稱)添加到列表中,然后再調用list.toArray(new Athlete [list.size()]); 這將為您提供所需的陣列
當然,您可以為文件中的每個記錄創建一個數組。 方法簽名看起來像例如
String[] readAthleteData() {...}
但是,使用諸如ArrayList之類的集合通常比數組更方便。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.