简体   繁体   English

C#-使用从文本文件中的行拆分数字

[英]C# - Using numbers split from lines in text file

I'm making a basic tax calculator which has to read from two lines in a text file using ReadLines, then split() these by the comma and use these numbers for calculations. 我正在制作一个基本的税收计算器,该计算器必须使用ReadLines从文本文件的两行中读取,然后用逗号split()并将其用于计算。 I can read and split the file fine, but actually referencing the split data for use in calculations isn't working as I'd hoped. 我可以很好地读取和拆分文件,但是实际上引用拆分数据以供计算时无法正常使用。 The text file is something like this: 文本文件是这样的:

500, 600, 700, 800, 900
0.1, 0.2, 0.3, 0.4, 0.5

And this is my code so far: 到目前为止,这是我的代码:

private void btnCalculateEmployeeTax_Click(object sender, EventArgs e)
    {
        string[] rates = File.ReadLines(@"E:\\path.txt").ToArray();

        string str1 = rates[0], str2 = rates[1];

        string[] income = str1.Split(',');
        string[] tax = str2.Split(',');

        int wages = 40*int.Parse(txtHourlyRate.Text);

        if (wages < income[0])
            {
            MessageBox.Show("Less than 500");
            MessageBox.Show ("Total tax is $" + (wages*tax[0]));

        }
        else
        {
            MessageBox.Show("More than 500");
        }

Obviously it's the code within the if/else statement that is kicking the error - this just gives you an idea of how I want to use the numbers. 显然是if / else语句中的代码引发了错误-这只是让您了解了我要如何使用数字。 Is there a way to assign each number from the text file to a local variable? 有没有一种方法可以将文本文件中的每个数字分配给局部变量? Or is there a work around for what I'm attempting here? 还是我在这里尝试的工作可以解决?

Apologies in advance for the rookie question. 提前为菜鸟问题道歉。

You can convert array to strings to array of ints. 您可以将数组转换为字符串并转换为整数数组。 You can do this like this 你可以这样

var result = income.Select(int.Parse).ToArray();

First if you wanna fix this you need to conver string into int 首先,如果您想解决此问题,则需要将string转换为int

 if (wages < int.Parse(income[0]))
 {
     MessageBox.Show("Less than 500");
     MessageBox.Show ("Total tax is $" + (wages*tax[0])); <- the same problem will be here
 }

But I think it will be better to create array of double instead of string 但是我认为创建double精度数组而不是string会更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM