首页 > 解决方案 > 我可以对我的代码做些什么来跳过输入文本文件的第一行?

问题描述

这是我的代码:

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

标签: java

解决方案


你可以做

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;
}

推荐阅读