开发者

Computing Average, High Score, Low Score using foreach loop

I have the following code. How would I make both one and two digit percentages work and not cause an exception?

private void calcStats()
{
    string value;
    int value2;
    int total = 0;
    decimal adverage;
    decimal high;
    decimal low;

    lblHigh.Text = Convert.ToString(0);

    foreach (string itemInList in lstBox.Items)
    {
        value = (itemInList.Substring(50, 3));
        value2 = int.Parse(value)开发者_运维知识库;

        total += (value2);
    }

   adverage = total/(lstBox.Items.Count);

   lblAdverage.Text = Convert.ToString(adverage);
}


Your problem this time is in another part of your code. In your btnAdd_Click method you have a code snippet like this:

    //Add the data elements to the row
    row = name.ToString().PadRight(25);
    row += ID.ToString().PadRight(25);
    row += score.ToString();

You need to pad the score as well:

    //Add the data elements to the row
    row = name.ToString().PadRight(25);
    row += ID.ToString().PadRight(25);
    row += score.ToString().PadRight(3);

Without the PadRight(3) Your single and two digit scores would throw an exception because that single digit was at the 50th position and there was nothing to read after that single digit. By padding it, you know have all 3 possible scores (single, double, triple digits) account for. The parse function will take care of the whitespace and just give you the number whether it's 1, 10, or 100.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜