[英]How to copy a line from a text file and print the line and line number
我在制作一个程序时会遇到麻烦,该程序会在文本文件中发现错误并打印错误所在的行,并打印错误所在的行号。 它正在寻找的错误是如果每行上有6个单词/数字,否则将出现错误
例如:
文本文件
名称品种月日年体重
名称繁殖月
名称品种月日年体重
***文件中的错误行:
名称繁殖月份第2行错误:字段数应为6,而不是3。 *
int numline= 0;
while(sc.hasNextLine())
{
// read a line from the input file via sc into line
line = sc.nextLine();
try{
StringTokenizer stk = new StringTokenizer(line);
String name = stk.nextToken();
String breed = stk.nextToken();
int month = Integer.parseInt(stk.nextToken());
int day = Integer.parseInt(stk.nextToken());
int year = Integer.parseInt(stk.nextToken());
double weight = Double.parseDouble(stk.nextToken());
numline++;
Dog list = new Dog(name, breed, month, day, year, weight);
dogs.add(list);
}
catch(Exception missError)
{
System.out.println("Error Lines detected in file:");
System.out.println("Number of fields on line must be 6");
}
}
// close the file
sc.close();
System.out.println(numline);
将numLine++
作为try
块的第一行,并在catch
块中使用它。 还可以使用line.split("\\\\s+");
它返回String[]
,您将事先知道字段的编号,因此您不必依赖Exception
。
int numLine= 0;
while(sc.hasNextLine())
{
line = sc.nextLine();
numLine++
String[] fields = line.split("\\s+");
if(fields.length != 6) {
System.out.println("Error Line number:"+numLine);
System.out.println("Number of fields on line must be 6, but it has :"+ fields.length);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.