【发布时间】:2014-09-17 03:22:18
【问题描述】:
我在编写一个程序时遇到了麻烦,该程序会在文本文件中找到错误并打印错误所在的行并打印错误所在的行号。它正在寻找的错误是每行是否有 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块中使用它。
标签: java string exception int stringtokenizer