【问题标题】:Issue with a do while loopdo while 循环的问题
【发布时间】:2017-12-02 09:43:45
【问题描述】:

以下程序会根据客户年龄来验证客户是否有资格观看某部电影。我遇到了 CustomerAgeCheck() 方法的问题。每次我输入年龄高于 100 或低于 0 时,循环都会继续无限运行,并且标签上不会显示任何结果。

protected void okButton_Click(object sender, EventArgs e)
    {
        AgeVerification();
        CostOfTickets();
    }
    protected int CustomerAgeCheck()
    {
        int age = int.Parse(Cust1AgeTextBox.Text);

        do
        {
            ageVerificationLabel.Text = String.Format("Please enter the correct age");

        } while (age < 0 || age > 100);

        return age;
    }
    protected void AgeVerification()
    {
        int age = CustomerAgeCheck();

        if (Movie3RadioButton.Checked && age < 17)
        {
            ageVerificationLabel.Text = String.Format("Access denied - you are too young");
        }
        else if (Movie4RadioButton.Checked || Movie5RadioButton.Checked || Movies6RadioButton.Checked && age < 13)
        {
            ageVerificationLabel.Text = String.Format("Access deniad - you are too young");
        }
        else
        {
            ageVerificationLabel.Text = String.Format("Enjoy your Movie");
        }
    }
    protected void CostOfTickets()
    {
        int cost;
        int totalTickets = int.Parse(CustomerDropDownList.SelectedValue);
        cost = totalTickets * 10;
        resultLabel.Text = String.Format("Your Total is {0:C}", cost);
    }     

【问题讨论】:

  • n 为什么要使用循环呢?在AgeVerification 中,您有类似的逻辑来进行输入验证。你为什么在CustomerAgeCheck 中切换到别的东西?请记住,如果这是 asp.net(基于您如何标记它),Cust1AgeTextBox.Text 中的值只会在用户再次发布表单后发生变化。您不能在循环中等待以等待新值的进入。这不是网络的工作方式。
  • 你永远不会改变age的值,所以条件总是为真。

标签: c# asp.net .net methods


【解决方案1】:

这是一个非常糟糕的逻辑,尤其是当您使用 GUI 并且您有事件可以帮助您时。

您所要做的就是添加一个 NumericUpDown 控件,将最小值设置为 0 并将最大值设置为 100,然后监听 ValueChanged 事件。

在这种情况下,您可以简单地使用上面的代码:

    age = (int)NumericUpDownAge.Value;
    if (Movie3RadioButton.Checked && age < 17)
    {
        ageVerificationLabel.Text = String.Format("Access denied - you are too young");
    }
    else if (Movie4RadioButton.Checked || Movie5RadioButton.Checked || Movies6RadioButton.Checked && age < 13)
    {
        ageVerificationLabel.Text = String.Format("Access deniad - you are too young");
    }
    else
    {
        ageVerificationLabel.Text = String.Format("Enjoy your Movie");
    }

您还可以根据在 NumericUpDown 中输入的年龄禁用/启用控件,并使您的 GUI 更具交互性和/或不言自明。

【讨论】:

  • 这是我在 HTML/Asp.Net 中所做的。输入年龄:
【解决方案2】:
do
        {
            ageVerificationLabel.Text = String.Format("Please enter the correct age");

        } while (age < 0 || age > 100);

问题很简单。它与上面的代码块一起使用。你没有休息条件。当您在年龄中输入大于 100 或小于 0 的值时,其值在循环执行中不会改变。因此while循环总是返回真(因为条件是只要年龄> 100和年龄

执行一次后输入其他值时,由于while循环条件失败,它将终止。

【讨论】:

  • OP 将他们的问题标记为 asp.net。 将年龄更新为 0 到 100 之间的值如果他们在某些网页中将其作为代码运行,则不会在循环中发生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 2013-09-26
  • 2016-01-03
相关资源
最近更新 更多