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],因为每一行被分成两行,对吗
# 1 楼答案
我觉得你应该一行一行地读,然后跳过10个字符,一直读到最后
# 2 楼答案
另一种方法是使用
Pattern
和Matcher