这是我的代码:
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
答案 0 :(得分:1)
可以做到
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;
}
答案 1 :(得分:0)
in the comments中所述的另一种解决方案是将演员表放在try
catch
块中。由于NumberFormatException
也可以在文件中的任何地方发生。
public static double columnSum(String filename, int column) {
double sum = 0;
Scanner scan = null;
try {
scan = new Scanner(new File(filename));
while (scan.hasNextLine()) {
String s = scan.nextLine();
try {
sum = sum + Double.parseDouble(s.split(",")[1]);
} catch (NumberFormatException n) {
// Do something else to handle it, or do nothing.
}
}
} catch (FileNotFoundException e) {
System.out.println("Inout file " + filename + " does not exist");
} finally {
scan.close(); // Close it regardless of the result
}
}