我被赋予了一项简单的任务,我似乎无法弄清楚如何完成它.
我收到了一个文本文件,其中包含员工的姓名和工资率/小时数.格式如下:
Mary Jones
12.50 30
Bill Smith
10.00 40
Sam Brown
9.50 40
Run Code Online (Sandbox Code Playgroud)
我的任务是编写一个程序,使用StreamReader从文本文件中提取数据,然后打印员工姓名,并通过乘以费率和小时来计算总工资.
我知道如何使用.Split方法拆分行,但我似乎无法弄清楚如何从双打/整数中分离名称.我的解析方法总是会返回格式错误,因为它首先读取字符串.我完全卡住了.
这是我的代码到目前为止,任何帮助或指导将不胜感激.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lab21
{
class Program
{
static void Main(string[] args)
{
StreamReader myfile = new StreamReader("data.txt");
string fromFile;
do
{
fromFile = myfile.ReadLine();
if (fromFile != null)
{
string[] payInfo = fromFile.Split( );
double wage = double.Parse(payInfo[0]);
int hours = int.Parse(payInfo[1]);
Console.WriteLine(fromFile);
Console.WriteLine(wage * hours);
}
} while (fromFile != null);
}
}
}
Run Code Online (Sandbox Code Playgroud)
你只是在循环中读一行.员工记录似乎由两行组成- 因此您需要在每次迭代时读取它们.(或者你可以跟踪你要去哪一行,但那会很痛苦.)我会把循环重写为:
string name;
while ((name = reader.ReadLine()) != null)
{
string payText = reader.ReadLine();
if (payText == null)
{
// Or whatever exception you want to throw...
throw new InvalidDataException("Odd number of lines in file");
}
Employee employee = ParseTextValues(name, payText);
Console.WriteLine("{0}: {1}", employee.Name, employee.Hours * employee.Wage);
}
Run Code Online (Sandbox Code Playgroud)
然后有一个单独的方法来解析这两个值,这将使它更容易测试.
在解析时,请注意您应该使用decimal而不是double表示货币值.