猪冰龙

导航

c#读取文本文档实践2-计算商品价格

商品 数量 单价
英语 66 100
语文 66 80
数学 66 100
化学 66 40
物理 66 60

上面是文本文档中读入的数据。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.IO;
 6 using System.Diagnostics;//Stopwatch所在命名空间
 7 
 8 namespace 书名总价格计算
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             string path = @"C:\Users\Administrator\Desktop\书名总价格计算.txt";
15             string[] contents = File.ReadAllLines(path, Encoding.Default);//将文档所有内容放入字符串数组中
16             Stopwatch sw = new Stopwatch();//创建一个计时器方法
17             sw.Start();//开始计时
18 
19             for (int i = 0; i < contents.Length; i++)//从第二行开始
20             {
21                 if (i != 0)
22                 {
23                     string[] strNew = contents[i].Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
24                     Console.WriteLine("{0} {1} {2} {3}", strNew[0], strNew[1], strNew[2], Convert.ToDouble(strNew[1]) * Convert.ToDouble(strNew[2]));
25                 }
26                 else//第一行题头不参与计算总价格
27                 {
28                     string[] strNew = contents[i].Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
29                     Console.WriteLine("{0} {1} {2} 总价格", strNew[0], strNew[1], strNew[2]);
30                 }
31             }
32             sw.Stop();//结束计时,以毫秒输出
33             Console.WriteLine(sw.ElapsedMilliseconds);//以毫秒形式输出结果
34         }
35     }
36 }

通过上述代码计算总价格输出到控制台上:

 

posted on 2016-08-29 11:05  猪冰龙  阅读(740)  评论(0编辑  收藏  举报