【问题标题】:Need help making a list accept multiple user inputs without removing the input before it需要帮助使列表接受多个用户输入而不删除之前的输入
【发布时间】:2012-10-24 22:17:52
【问题描述】:

我需要帮助为我的班级制作分数计算器。分数的输入不能预先设置,它必须在增加计数的同时将所有先前的输入相加。

例如,假设我在文本框中输入 23,然后按 Enter,然后输入 45,我需要我的程序保留 23 并将其添加到 45,只要用户输入数字,它就需要重复此操作。

我知道它需要是一个集合,并且我已经有了它的基础,我只需要代码来保存以前的输入并将其添加到新的输入中并保存总计以将其添加到下一个输入中。

这是我解决这个问题的尝试:

 List<decimal> score = new List<decimal>();
        score.Add(scoreInput);
        decimal scoreTotal = 0;
        decimal scoreHolder = 0;
        foreach (decimal d in score)
        {

            scoreTotal = scoreHolder + scoreInput;
            scoreHolder = scoreInput;
            scoreInput = 0;
            txtTotal.Text = scoreTotal.ToString("");
            txtCount.Text = score.Count.ToString("");
            txtScore.Clear();
            txtScore.Focus();
        }

【问题讨论】:

  • 你能声明一个变量sum吗?
  • 到目前为止你有什么?可以发一点代码吗?
  • 您需要提供更多详细信息,例如这是 Web 窗体、Windows 窗体、控制台还是其他类型的应用程序。此外,您应该显示一些您已经尝试过的代码。人们很愿意提供建议,但不想觉得他们在为你做功课。
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。

标签: c# winforms collections


【解决方案1】:

只需为 KeyDown 事件添加一个事件处理程序,并使用如下代码:

private void tbEntry_KeyDown(object sender, KeyEventArgs e)
{
    Decimal entry;

    if (e.KeyCode == Keys.Enter)
    {
        if (Decimal.TryParse(tbEntry.Text, out entry))
        {
            score.Add(entry);
        }

        tbResult.Text = score.Sum(s => s).ToString();
        tbEntry.Text = string.Empty;
    }
}

这是实现您想要实现的目标的一种方式。

编辑:

这是假设您将变量“score”声明为表单的成员:

private  List<decimal> score = new List<decimal>();

干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多