0

I have a program I have to finish which involves opening a file that has numbers, displaying it, then also displaying how many numbers the file has and the sum of them.

Im currently stuck on how to add all the numbers read and display it :/

Here is my code:

private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
    StreamReader inputFile;
    try
    {
        int number = 0;
        int count = 0;
        int sum = 0;
        lstRandomNumbers.Items.Clear();

        if (fodOpenFile.ShowDialog() == DialogResult.OK)
        {
            inputFile = File.OpenText(fodOpenFile.FileName);
            lstRandomNumbers.Items.Clear();

            while (!inputFile.EndOfStream)
            {
                number = int.Parse(inputFile.ReadLine());

                count = count + 1;
                lstRandomNumbers.Items.Add(number);
            }

            lblNumberCount.Text = count.ToString();
            lblSumNumbers.Text = number.ToString();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("There is a problem with the disk file." + Environment.NewLine + ex.Message, "User Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

As seen in the Picture, the sum is only reading the last number of the list and im not sure why

Thanks for reading!

vasily.sib
  • 3,871
  • 2
  • 23
  • 26
  • 3
    Try this: `File.ReadLines(@"").Select(x => int.Parse(x)).Aggregate(new { count = 0, sum = 0 }, (a, x) => new { count = a.count + 1, sum = a.sum + x })`. – Enigmativity Mar 20 '19 at 03:22
  • You're only putting the last number up because you've written `lblSumNumbers.Text = number.ToString();`. You're not summing the numbers in any way. `number` is overwritten in the loop with latest number in `number = int.Parse(inputFile.ReadLine())`. – Enigmativity Mar 20 '19 at 03:23
  • @Enigmativity answer it up – TheGeneral Mar 20 '19 at 03:31
  • Yes, you have the sum variable, but it's not currently being used. – Ben Mar 20 '19 at 03:33
  • By using Linq with File.ReadAllLines and let you will get sum and count of numbers. You can refer [Read File using Linq](https://stackoverflow.com/a/5116696/9994702). – Hardik Dhankecha Mar 20 '19 at 03:43

4 Answers4

1

in line number = int.Parse(inputFile.ReadLine()); replaced number for each line!

you can write all code with this:

private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
    try
    {
        lstRandomNumbers.Items.Clear();

        if (fodOpenFile.ShowDialog() == DialogResult.OK)
        {
            var linesOfFile = File.ReadAllLines(fodOpenFile.FileName).Select(int.Parse).ToList();
            lblSumNumbers.Text = linesOfFile.Sum().ToString();
            lblNumberCount.Text = linesOfFile.Count().ToString();
            lstRandomNumbers.DataSource = linesOfFile;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("There is a problem with the disk file." + Environment.NewLine + ex.Message, "User Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}
vasily.sib
  • 3,871
  • 2
  • 23
  • 26
HGH System
  • 23
  • 6
0

You are almost there. Try your same code with minor modification. I have added inline comments.

private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
    StreamReader inputFile;
    try
    {
    int number = 0;
    int count = 0;
    int sum = 0;
    //lstRandomNumbers.Items.Clear(); //don't need this

    if (fodOpenFile.ShowDialog() == DialogResult.OK)
    {
        inputFile = File.OpenText(fodOpenFile.FileName);
        //lstRandomNumbers.Items.Clear();//don't need this

        while (!inputFile.EndOfStream)
        {
            number = int.Parse(inputFile.ReadLine());

            count = count + 1;
            //lstRandomNumbers.Items.Add(number);//don't need this
            sum+=number; // add this
        }

        lblNumberCount.Text = count.ToString();
        lblSumNumbers.Text = sum.ToString(); //change `number' to `sum`
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show("There is a problem with the disk file." + Environment.NewLine + ex.Message, "User Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

@Issa, Please let me know if this helps.

Ajeet Kumar
  • 687
  • 6
  • 12
  • you first parse number from file: `number = int.Parse(inputFile.ReadLine());` then convert it to string and parse again: `sum+= Int32.Parse(lblSumNumbers.Items[i].ToString());` maybe it is better to parse it only once? – vasily.sib Mar 20 '19 at 04:11
  • @vasily, very correctly pointed. Though, the first `int.Parse` should check/validate if the value is integer through `int.TryParse`, the second parse is required in order to cast to integer in order to sum. – Ajeet Kumar Mar 20 '19 at 04:21
  • As original question didn't use `int.TryParse` - I assume, that they 100% sure, that file contains **only** valid integers. You don't need the second parse, if you just add `sum += number;` line to your `while (!inputFile.EndOfStream)` loop. – vasily.sib Mar 20 '19 at 04:30
0

Give this a go:

private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
    if (fodOpenFile.ShowDialog() == DialogResult.OK)
    {
        var lines = File.ReadAllLines(fodOpenFile.FileName);

        var result =
            lines
                .Select(x => int.Parse(x))
                .Aggregate(
                    new { count = 0, sum = 0 },
                    (a, x) => new { count = a.count + 1, sum = a.sum + x });

        lstRandomNumbers.Items.Clear();
        lstRandomNumbers.Items.AddRange(lines);
        lblNumberCount.Text = result.count.ToString();
        lblSumNumbers.Text = result.sum.ToString();
    }
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
-1
  static void Main(string[] args)
    {
        var res = 0;
        var r = new Regex(@"\d");// you can try "\d+" and you will see the difference
        var matches = r.Matches("feawfwe312faewfa4gaeg1feaga67awfaw2");
        if (matches != null && matches.Count > 0)
        {
            foreach (var m in matches)
                res += int.Parse(m.ToString());
        }
        Console.WriteLine(res);
        Console.ReadKey();
    }
hugh lu
  • 41
  • 1