文本框空问题

发布于 2024-11-30 18:04:20 字数 1822 浏览 0 评论 0原文

所以基本上我正在尝试制作一个 Windows 窗体应用程序来计算 4 个测试成绩的平均值。然而,在某些课程中,我可能只有3次测试。如果所有四个测试文本框中没有值,程序将不会计算平均值。我正在尝试找出一种编码方法,如果第四个文本框中没有任何内容,只需忽略它并计算其他 3 个文本框。我的代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GradeCalc
{
    public partial class Grades : Form
    {
        public Grades()
        {
            InitializeComponent();
        }

        private void Submit_Click(object sender, EventArgs e)
        {
            double test1;
            double test2;
            double test3;
            double test4;
            double average4;
            double average3;

            //Here, I'm trying to achieve:
            //if (t4 is empty)
            //{find the average of the first 3 textboxes}

            if (t4.Text == null)
            {
                test1 = double.Parse(t1.Text);
                test2 = double.Parse(t2.Text);
                test3 = double.Parse(t3.Text);
                average3 = ((test1 + test2 + test3) / 3);
                tavg.Text = average3.ToString("00.00");
            }
                //Here, I'm trying to achieve:
                //if (t4 is not empty)
                //{ calculate the average of all 4 textboxes}

            else
                if (t4.Text != null)
                {
                    test1 = double.Parse(t1.Text);
                    test2 = double.Parse(t2.Text);
                    test3 = double.Parse(t3.Text);
                    test4 = double.Parse(t4.Text);
                    average4 = ((test1 + test2 + test3 + test4) / 4);
                    tavg.Text = average4.ToString("00.00");
                }
        }
    }
}

我对 C# 没有太多经验,因此任何帮助都会不胜感激。

So basically I'm trying to make a Windows Form Application to calculate the average of 4 test grades. However, in some classes, I may only have 3 tests. Without a value in all four test textboxes the program will not calculate the average. I'm trying to figure out a way to code if the fourth text box has nothing in it, just ignore it and calculate the other 3. My code is below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GradeCalc
{
    public partial class Grades : Form
    {
        public Grades()
        {
            InitializeComponent();
        }

        private void Submit_Click(object sender, EventArgs e)
        {
            double test1;
            double test2;
            double test3;
            double test4;
            double average4;
            double average3;

            //Here, I'm trying to achieve:
            //if (t4 is empty)
            //{find the average of the first 3 textboxes}

            if (t4.Text == null)
            {
                test1 = double.Parse(t1.Text);
                test2 = double.Parse(t2.Text);
                test3 = double.Parse(t3.Text);
                average3 = ((test1 + test2 + test3) / 3);
                tavg.Text = average3.ToString("00.00");
            }
                //Here, I'm trying to achieve:
                //if (t4 is not empty)
                //{ calculate the average of all 4 textboxes}

            else
                if (t4.Text != null)
                {
                    test1 = double.Parse(t1.Text);
                    test2 = double.Parse(t2.Text);
                    test3 = double.Parse(t3.Text);
                    test4 = double.Parse(t4.Text);
                    average4 = ((test1 + test2 + test3 + test4) / 4);
                    tavg.Text = average4.ToString("00.00");
                }
        }
    }
}

I do not have a lot of experience with C#, so any help would be appreciated thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

坏尐絯 2024-12-07 18:04:21

尝试 String.IsNullOrEmpty(t4.Text)

Try String.IsNullOrEmpty(t4.Text)

留一抹残留的笑 2024-12-07 18:04:21

试试这个:

List<double> MyValues = new List<double>;

double T;

if ( double.TryParse ( t1.Text, out T) )
     MyValues.Add (T);

if ( double.TryParse ( t2.Text, out T) )
     MyValues.Add (T);

if ( double.TryParse ( t3.Text, out T) )
     MyValues.Add (T);

if ( double.TryParse ( t4.Text, out T) )
     MyValues.Add (T);

if ( MyValues.Count > 0 )
     tavg.Text = MyValues.Average ().ToString ("00.00");

上面的代码很强大...如果任何文本 (t1 - t4) 不是有效数字,则会跳过...计算正确值的平均值(无论是 1、2、3或 4) 仅...并且它会处理未输入有效值的情况...

您可以轻松修改它,要求在更改最后一个 ifif ( MyValues.Count > 3) 例如。

try this:

List<double> MyValues = new List<double>;

double T;

if ( double.TryParse ( t1.Text, out T) )
     MyValues.Add (T);

if ( double.TryParse ( t2.Text, out T) )
     MyValues.Add (T);

if ( double.TryParse ( t3.Text, out T) )
     MyValues.Add (T);

if ( double.TryParse ( t4.Text, out T) )
     MyValues.Add (T);

if ( MyValues.Count > 0 )
     tavg.Text = MyValues.Average ().ToString ("00.00");

the code above is robust... if any of the texts (t1 - t4) is not a valid number it is skipped... the average is calculated for the correct values (whether 1, 2, 3 or 4) only... and it takes care of the case that no valid value has been entered...

You could easily modify it to require that at least 3 valid numbers are entered bei changing the last if to if ( MyValues.Count > 3 ) for example.

拧巴小姐 2024-12-07 18:04:21

第四个文本框的内容可能不为空,而只是一个空字符串。您可以使用 String.IsNullOrEmpty() 而不是与 null 进行比较来覆盖所有角度。但如果有人插入空格或其他东西怎么办?您可能还想删除空白。

完全的替代方案是使用 TryParse 方法而不是 Parse - 然后使用返回的成功布尔值来决定您有多少结果。 TryParse 的工作原理如下:

if (Double.TryParse(t4.Text, out test4))
{
   // this works
}
else
{
   // this did not
}

The fourth textbox's content is probably not not null but just an empty string. You could use String.IsNullOrEmpty() rather than the comparison with null to cover all angles. But what if someone puts in a space or something. You might want to trim out whitespace too.

A total alternative would be to use the TryParse method rather than Parse - and then use the returned success boolean to decide how many results you have. TryParse works like this:

if (Double.TryParse(t4.Text, out test4))
{
   // this works
}
else
{
   // this did not
}
九八野马 2024-12-07 18:04:21

您可以通过解耦您想要执行的各种任务来改进您的代码。最初您想要解析文本框中的数字。您可以使用函数来做到这一点:

IEnumerable<Double> ParseValues(IEnumerable<TextBox> textBoxes) {
  foreach (var textBox in textBoxes) {
    Double value;
    if (Double.TryParse(textBox.Text, out value))
      yield return value;
  }
}

此函数将采用 TextBox 对象的输入序列,并生成 Double 值的输出序列,跳过所有具有无效值的文本框。

然后,您可以使用此函数来计算平均值:

var values = ParseValues(new[] { t1, t2, t3, t4 });
if (values.Any()) {
  var average = values.Average();
  tavg.Text = average.ToString("00.00");
}

如果任何或所有文本框包含有效值,则此代码将计算平均值。

You can improve your code by decoupling the various tasks you want to undertake. Initially you want to parse the numbers in the text boxes. You can do that using a function:

IEnumerable<Double> ParseValues(IEnumerable<TextBox> textBoxes) {
  foreach (var textBox in textBoxes) {
    Double value;
    if (Double.TryParse(textBox.Text, out value))
      yield return value;
  }
}

This function will take an input sequence of TextBox objects and produce an output sequence of Doublevalues skipping all text boxes with invalid values.

You can then use this function to computer the average:

var values = ParseValues(new[] { t1, t2, t3, t4 });
if (values.Any()) {
  var average = values.Average();
  tavg.Text = average.ToString("00.00");
}

This code will compute the average if any or all of the text boxes contain valid values.

一人独醉 2024-12-07 18:04:21

请参阅讨论 TryParse 或文本框内容的其他答案。这只是对这些的注释。

FWIW,我有帮助函数来让生活更轻松,例如:

double? AsDouble (string str) {
  double value;
  if (double.TryParse(str, out value))
    return value;
  } else {
    return null;
  }
}

然后就很简单:(

double val = AsDouble(txt.Text) ?? 0;

其中 0 是默认的数字。)

快乐编码。

See the other answers that talk about TryParse or the contents of the text-box. This is just an annotation to those.

FWIW, I have helper functions to make life easier, for instance:

double? AsDouble (string str) {
  double value;
  if (double.TryParse(str, out value))
    return value;
  } else {
    return null;
  }
}

Then it's as easy as:

double val = AsDouble(txt.Text) ?? 0;

(Where 0 is the number to default to.)

Happy coding.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文