我创建了一个扫描器类来读取文本文件并获得我想要的值。假设我有一个文本文件包含。
人员名单:长度3
1 : Fnjiei : ID 7868860 : 18 岁
2 : Oipuiieerb : ID 334134 : 39 岁
3 : Enekaree : ID 6106274 : 31 岁
我正在尝试获取姓名和身份证号码和年龄,但每次我尝试运行我的代码时,它都会给我一个例外。这是我的代码。java 大师有什么建议吗?:) 它能够读取一行.......但不超过一行文本。
public void readFile(String fileName)throws IOException{
Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader(fileName)));
try {
while (input.hasNextLine()){
int howMany = 3;
System.out.println(howMany);
String userInput = input.nextLine();
String name = "";
String idS = "";
String ageS = "";
int id;
int age;
int count=0;
for (int j = 0; j <= howMany; j++){
for (int i=0; i < userInput.length(); i++){
if(count < 2){ // for name
if(Character.isLetter(userInput.charAt(i))){
name+=userInput.charAt(i); // store the name
}else if(userInput.charAt(i)==':'){
count++;
i++;
}
}else if(count == 2){ // for id
if(Character.isDigit(userInput.charAt(i))){
idS+=userInput.charAt(i); // store the id
}
else if(userInput.charAt(i)==':'){
count++;
i++;
}
}else if(count == 3){ // for age
if(Character.isDigit(userInput.charAt(i))){
ageS+=userInput.charAt(i); // store the age
}
}
id = Integer.parseInt(idS); // convert id to integer
age = Integer.parseInt(ageS); // convert age to integer
Fighters newFighters = new Fighters(id, name, age);
fighterList.add(newFighters);
}
userInput = input.nextLine();
}
}
}finally{
if (input != null){
input.close();
}
}
}
如果我的代码需要更改,我会道歉。
编辑它给了我一个数字格式异常!!!我不知道这些值之间会有多少空白。