如何修复此验证? C#

时间:2013-11-19 17:09:34

标签: c# validation binary decimal

好的,我已经将一个基本的二进制转换器变成了十进制,我正在尝试验证用户输入,因此它只能是0或1,这在第一次工作正常,如果他们输入一个不正确的值,它要求他们重新输入它,但如果他们第二次键入不正确的值会出现问题,我将如何解决此问题?或者喜欢将它循环回程序的特定部分?非常感谢,这是我的代码:

if (iBinaryNum1 == 1 || iBinaryNum1 == 0)
{
  Console.WriteLine("The binary value entered for integer 1 is correct");
}
else
{
  Console.WriteLine("The binary value entered for integer 1 is incorrect");
  Console.WriteLine("Please Re-enter this value");
  iBinaryNum1 = Convert.ToInt32(Console.ReadLine());
}

5 个答案:

答案 0 :(得分:5)

是的,我建议使用循环。例如(伪代码)

bool validValue = false;
while(!validValue)
{
  // Get input from the user
  // Print a message and set validValue
  // As soon as you set validValue to false the loop will break
}

// Your value will be valid here.

另外,请注意Convert.ToInt32 - 如果输入无效值,则会引发异常。您可以查看int.TryParse

答案 1 :(得分:1)

改为使用while循环:

  iBinaryNum1 = ReadValue();
  iBinaryNum2 = ReadValue();

  while (!(iBinaryNum1 == 1 || iBinaryNum1 == 0))
  {
    Console.WriteLine("The binary value entered for integer 1 is correct");
    iBinaryNum1 = ReadValue();
    iBinaryNum2 = ReadValue();
  }

您必须将阅读功能分成一个单独的功能才能重复调用。然后放入一个不会继续接受的while循环,直到输入正确的值。

答案 2 :(得分:1)

将其包裹在do while循环中

    do {
    if (iBinaryNum1 == 1 || iBinaryNum1 == 0)
    {
        Console.WriteLine("The binary value entered for integer 1 is correct");
    }
    else
    {
        Console.WriteLine("The binary value entered for integer 1 is incorrect");
        Console.WriteLine("Please Re-enter this value");
        iBinaryNum1 = Convert.ToInt32(Console.ReadLine());
    }
} while (iBinaryNum1 ! = 999);

如果输入999或某个退出值,它将退出循环。

答案 3 :(得分:1)

答案实际上非常简单,不确定您是否找到了解决方案,但执行此验证的最佳方法是将所有if语句一起删除并使用如下所示的while循环:

while (iBinaryNum1 < 0 || iBinaryNum1 > 1)
        {
            Console.WriteLine("The value entered was incorrect");
            Console.WriteLine("Please Re-enter this value: ");
            iBinaryNum1 = Convert.ToInt32(Console.ReadLine());
        }

这将不断提示用户重新输入值,直到它们正确

答案 4 :(得分:0)

如果这是Windows窗体/ WPF应用程序,您可以通过对输入控件(如TextBox,NumericUpDown或MaskedTextBox等)应用限制来限制用户仅输入有效值。