Onejo578
Onejo578

Reputation: 13

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. 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. 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.

Upvotes: 0

Views: 272

Answers (2)

Krzysztof Wrona
Krzysztof Wrona

Reputation: 311

You can convert array to strings to array of ints. You can do this like this

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

Upvotes: 1

Roman Marusyk
Roman Marusyk

Reputation: 24589

First if you wanna fix this you need to conver string into 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

Upvotes: 0

Related Questions