我想用名字填充数组。应该根据角色的性别来填充数组。
public void fillNameArray() throws IOException {
Character character = new Character(); //Declare and initialise character object
if(character.getGender() == "F"){
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("femaleNames.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
String[] array = (String[]) lines.toArray();
}
else{
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("maleNames.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
String[] array = (String[]) lines.toArray();
}
}
答案 0 :(得分:0)
问题出在以下几行:
String[] array = (String[]) lines.toArray();
改为写:
String[] array = lines.toArray(new String[lines.size()]);
请参阅post作为示例。
请问您还可以使用自己的方法移动读取代码吗?所以代码重复较少。
public List<String> readNames(String file) {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
return lines;
}