如何只读取文件中的双精度值

时间:2014-07-15 05:21:17

标签: java

我有一个像这样的文件

07/15/14: 19.33

07/15/14: 13.14

07/15/14: 21.20

07/15/14: 22.67

我需要一种方法来读取这些双精度值并打印出平均值。这就是数字的保存方式。

public void hourlyOverall() throws IOException
{
    //construct the date to print into a file
    java.sql.Date date=new java.sql.Date(time);
    //set hourlyOverall variable
    hourlyOverall=tips/hours+hourlyWage;
    //construct the printwriter with a file writer in it.  
    //set the FileWriter append parameter too true so that the 
    //info is added onto the end of the file, and the file is
    //not overwritten
    PrintWriter editFile=new PrintWriter(new FileWriter("wage info",true));
    editFile.printf("%tD: %.2f \n ", date, hourlyOverall);
    editFile.close();
}

这就是我试图阅读它们的方式。

public double totalHourlyOverall() throws FileNotFoundException
{
    Scanner fileScanner=new Scanner(fos);
    while(fileScanner.hasNextDouble())
    {
            total+=fileScanner.nextDouble();
            counter+=1;
    }
    fileScanner.close();
    return overallHourly=total/counter;
}
但是,它并没有拿到双打。我做错了什么?

编辑:

所以我现在得到一个超出界限的数组。我的代码就像这样

public double totalHourlyOverall() throws FileNotFoundException

{
    Scanner fileScanner=new Scanner(fos);
    while(fileScanner.hasNextLine())
    {
            String str=fileScanner.nextLine();
            String[] array=str.split(":");
            total+=Double.parseDouble(array[1]);
            counter+=1;
    }
    fileScanner.close();
    return overallHourly=total/counter;
}

应该有一个数组[1]因为每一行被分成两行,对吧?

4 个答案:

答案 0 :(得分:2)

有一种更简单的方法:读取每一行,并拆分行中的公共标记。

我不会写出所有代码,但这是一种阅读整行的方法:

while(fileScanner.hasNextLine()) {
    String line = fileScanner.nextLine();
    String[] lineFragments = line.split(":");
    // the date is in lineFragments[0]; the number is in lineFragments[1].
    // I leave the rest as an exercise to the reader.
}

答案 1 :(得分:2)

hasNextDouble将在“07/15/14”返回false,你将在那里停止阅读。

答案 2 :(得分:0)

另一种方法是使用PatternMatcher

Pattern p = Pattern.compile("(\\b[-\\d\\.]+\\b)");   // pattern to match any double value (+/-) with boundaries
Matcher m;
while(fileScanner.hasNextLine()) {
    String line = fileScanner.nextLine();
    m = p.matcher(line); // try to match the regular expression
    if ( m.find() ) {
        String value = m.group(1); // get the match in group 1
        // turn to a double, etc...
    }
}

答案 3 :(得分:-1)

我认为你应该逐行阅读,然后跳过10个字符,然后读到行尾。

相关问题