简体   繁体   English

Int&Float Max值的控制台应用程序输入验证C#

[英]Console Application Input Validation for Int & Float Max Values C#

I am building an application that takes two inputs from user. 我正在构建一个从用户那里获取两个输入的应用程序。 One int and the other float. 一个int和另一个浮点数。 int.MaxValue and float.MaxValue are the two properties I am using to validate the input. int.MaxValuefloat.MaxValue是我用来验证输入的两个属性。

However, the input is built in such a way by adding each KeyChar because each key input has to be validated during Key press event as application restricts users to number (whole/decimal). 但是,通过添加每个KeyChar以这种方式构建输入,因为在按键事件期间必须验证每个键输入,因为应用程序将用户限制为数字(整数/小数)。

Here the code so far: 这里的代码到目前为止:

ConsoleKeyInfo key;
const int intMaxValue = int.MaxValue;
const float floatMaxValue = float.MaxValue;
bool validated;
int tempAmount;
int intAmount;
string tempVal="";

do{
    key = Console.ReadKey (true);
    if (key.Key != ConsoleKey.Backspace)
    {                    
       validated  = int.TryParse (key.KeyChar.ToString(), out tempAmount);
       if (validated)
       {
          ///Full amount is built here
          tempVal += key.KeyChar;
  //Fails here--->> as Type Cast happens on a String which hold a value beyond an int
          if (int.Parse(tempVal) < intMaxValue)
          {                    
             intAmount = int.Parse(tempVal);
             Console.Write(key.KeyChar);                         
          }

I could do this test after user has pressed Enter Key. 用户按下Enter键后,我可以进行此测试。 However still it will be failed. 但是它仍然会失败。 Becuase there's no way an int could hold beyond its max Value.. 因为int无法超越其最大值...

Thus I came up with the following: However it doesn't feel efficient as my second input validation is based on float .... 因此我想出了以下内容:然而,由于我的第二个输入验证基于float效率不高。

if (float.Parse(tempVal) < intMaxValue)
{

Therefore someone please show me an efficient property of int, float class that can be used in the two scenarios.. OR any other way to sew the input while validating each key digit by digit until user enters Enter key. 因此有人请告诉我一个有效的int属性,可以在两种情况下使用的浮点类。 或者在用户输入Enter键之前逐个验证每个键的任何其他方式来缝制输入。

You could try using TryParse . 您可以尝试使用TryParse TryParse will evaluate to false if the value isn't a valid Int32 (if will be false if it exceeds Int32.MaxValue ). 如果值不是有效的Int32 ,则TryParse将计算为false(如果超过Int32.MaxValue false)。

int realValue;

if (Int32.TryParse(tempVal, out realValue))
   {                    
      intAmount = int.Parse(tempVal);
      Console.Write(key.KeyChar);                         
   }

You can also use the corresponding float.TryParse to test the float values you expect. 您还可以使用相应的float.TryParse来测试您期望的浮点值。

You can try this: 你可以试试这个:

if (validated)
   {
      ///Full amount is built here 
      long l = long.Parse(tempVal + key.KeyChar);        
      if (l < intMaxValue)
      {                    
         intAmount = (int)l;
         tempVal += key.KeyChar;
         Console.Write(key.KeyChar);                         
      }

However, as others suggested, you should use Console.ReadLine and use TryParse in combination with a while loop until the input is validated . 但是,正如其他人所建议的那样,您应该使用Console.ReadLine并将TryParsewhile循环结合使用while直到validated输入为止。

After some deeper scan into your code, I think yo don't need the tempVal when you already have intAmount , just do something like this: 经过一番更深入的扫描到你的代码,我想哟不需要tempVal当你已经有intAmount ,只是做这样的事情:

 if (validated)
   {
      long k = intAmount*10L + (int) key.KeyChar - 48;
      if (k < intMaxValue)
      {                    
         intAmount = (int)k;
         Console.Write(key.KeyChar);                         
      }         

Working with ReadLine will be easier 使用ReadLine会更容易

bool validated = false;
int integerRequired;
Console.WriteLine("Type an integer number:");
while(validated == false)
{    
    string userInput = Console.ReadLine();
    validated  = int.TryParse (userInput, out integerRequired);
    if (!validated )
        Console.WriteLine("Not a valid integer, please retype a valid integer number");
}

float singleRequired;
validated = false;
Console.WriteLine("Type a floating point number:");
while(validated == false)
{    
    string userInput = Console.ReadLine();
    validated  = Single.TryParse (userInput, out singleRequired);
    if (!validated)
        Console.WriteLine("Not a valid float, please retype a valid float number");
}

In this example, you react to the user input only when he finishes to type and press enter. 在此示例中,仅在完成输入并按Enter键时才对用户输入作出反应。 At this point you could evaluate the input using the version of TryParse appropriate for the input and choose to display or not an error message to the user. 此时,您可以使用适合输入的TryParse版本评估输入,并选择向用户显示或不显示错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM