简单利用Scanner对文件进行解析

public class AvPrice
{
    static int count = 0;
    static int sum = 0;
    public static void main(String[] args)
    {
        try
        {

    //定义并实例化Scanner对象
            Scanner in = new Scanner(new File("d:/abc.txt"));

    //如果有下一行就返回true
            while (in.hasNextLine())
            {

      //获取下一行
                String str = in.nextLine();

      //调用spilitt方法进行分割
                splitt(str);
            }
            System.out.println("sum:" + sum + " " + "average:" + sum / count);

        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
    }

    public static String[] splitt(String str)
    {

   //去空格
        String strr = str.trim();

    //以逗号为分隔符
        String[] abc = strr.split(",");

   //以汉字元为分隔符
        String[] ab = abc[1].split("元");

   //把String类型数据转化成Double类型
        Double temp = new Double(ab[0]);

   //求和
        sum += temp;

   //计数
        count++;

   //返回
        return abc;
    }
}

posted @ 2016-11-29 22:05  qingtianBKY  阅读(430)  评论(0编辑  收藏  举报