这是我的代码:
public static double columnSum(String filename, int column) {
double sum = 0;
try {
Scanner scan = new Scanner(new File(filename));
while (scan.hasNextLine()) {
String s = scan.nextLine();
sum = sum + Double.parseDouble(s.split(",")[1]);
}
} catch (FileNotFoundException e) {
System.out.println("Inout file " + filename + " does not exist");
}
return sum;
}
我想尝试跳过文本文件的第一行,以避免 NumberFormatException
我收到错误,但我不知道如何处理我的代码来做到这一点。
这是要读取的文件的示例
Date,Temperature High,Temperature Low,Rain
Junk line useless, data, at, every, column, in, this, line
Sat 3/7/2015,62,26,0
Sun 3/8/2015,51,46,0.23
Sat 3/14/2015,68,56,0
useless, data, at, every, column, in, this, line.
Sun 3/15/2015,69,54,0
Mon 3/30/2015,78,60,0
Tue 3/31/2015,84,65,0
Wed 4/1/2015,81,66,0.04
Thu 4/2/2015,85,69,0
Fri 4/3/2015,74,60,0
More junk
Sat 4/18/2015,82,58,0.21
Sat 4/25/2015,87,54,0
Sun 4/26/2015,85,58,0.12
Even more useless data.
Sat 7/4/2015,94,77,0
Sun 7/5/2015,84,79,0
Mon 7/6/2015,93,78,0
最佳答案
你可以做到
Scanner scan = new Scanner(new File(filename));
// skip first line
if(scan.hasNextLine()){
scan.nextLine();
}
// then read the rest
while(scan.hasNextLine()){
String s = scan.nextLine();
sum = sum + Double.parseDouble(s.split(",")[1]);
}
另外,不要忘记关闭扫描仪
。那么你的代码应该是这样的
public static double columnSum(String filename, int column) {
double sum = 0;
try(Scanner scan = new Scanner(new File(filename))) {
if(scan.hasNextLine()){
scan.nextLine();
}
while (scan.hasNextLine()) {
String s = scan.nextLine();
sum = sum + Double.parseDouble(s.split(",")[1]);
}
} catch (FileNotFoundException e) {
System.out.println("Inout file " + filename + " does not exist");
}
return sum;
}
关于java - 我可以对代码执行哪些操作来跳过输入文本文件的第一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53562551/