java - 我可以对我的代码做些什么来跳过输入文本文件的第一行?
问题描述
这是我的代码:
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]);
}
另外,不要忘记关闭Scanner
. 那么你的代码应该是这样的
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;
}
推荐阅读
- html - 在 Netlify.toml 文件中设置多个重定向
- r - 仅对缺失日期使用滞后函数递增日期
- date - 在SAS中的多个主题的日期条目之间创建唯一日期列表?
- reactjs - Draft.js - createWithContent 或 convertFromRaw 抛出错误
- java - Artifactory REST API 拒绝有效的 JSON
- haskell - 如何解释 Haskell 中的关联性/优先级
- reactjs - 如何在 axios.get 中添加正文?
- linux - Bash - 多行 Whiptail 反标题
- python - 避免使用双引号将 pandas.to_sql 写入表(PostgreSQL 数据库)
- c++ - 如何在 C++ 中使用双链表实现迭代器前后方法?