[英]How to read a line from a txt file with int and String elements?
我正在尝试通过阅读txt文件来创建列表。 例如:
12345; Mary Jane ; 20
12365; Annabelle Gibson; NA
每行包含:数字; 名称; 等级(等级可以是字符串或整数)
我创建了以下方法;
public static List <Pauta>leFicheiro( String nomeF) throws FileNotFoundException{
List<Pauta> pautaT = new LinkedList<Pauta>();
try {
Scanner s = new Scanner(new File (nomeF));
try{
List<Pauta> pautaS =pautaT;
while ( s.hasNextLine()){
String line = s.nextLine();
String tokens[]= line.split(";");
if(s.hasNextInt()) {
System.out.println ("next int = " + s.nextInt());
}
pautaS.add(new Pauta (s.nextInt(), tokens[1],tokens[2]);
}
pautaT = pautaS;
}
finally {
s.close();
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (ParseException e){
e.printStackTrace();
}
return pautaT;
}
Pauta是一类作为参数(int,String,String)接收的类,我认为将Grade作为一个String使其更简单,但是如果您对如何通过使用String或int来创建列表(主要目标)有想法我会很感激。
现在的问题是:部分s.nextInt()返回错误:InputMismatchException
所以我把下面的代码:
catch (InputMismatchException e) {
System.out.print(e.getMessage());}
表示返回null。
我该如何解决?
代替使用s.nextInt(),将第一个标记解析为Integer。
请参见下面的示例。
public static void main(String... args) throws FileNotFoundException {
List<Pauta> pautaT = new LinkedList<Pauta>();
try {
Scanner s = new Scanner(new File("test.txt"));
try{
List<Pauta> pautaS =pautaT;
while ( s.hasNextLine()){
String line = s.nextLine();
String tokens[]= line.split(";");
pautaS.add(new Pauta (Integer.parseInt(tokens[0]), tokens[1],tokens[2]));
}
pautaT = pautaS;
}
finally {
s.close();
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
这将导致列表被填充。
您可能会使用StringTokenizer,并将同一行的每个标记保存到变量中,然后根据需要使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.