Hi,
here the question.. i wanted to knw if i can set the limit of the input that user can keyin only 4 integers number.. by default, i use this kind of code ..
input:
Console.WriteLine("4 integers number");
Console.Write(" User input: ");
int j = int.Parse(Console.ReadLine());
if ((j < 1000) || (j > 10000))
{
Console.Clear();
Console.WriteLine("Error!!Please input 4 digit integers");
goto input;
}
by the way, if u see the code.. 0000-0999 cant be read since the condition is 1000-10000..
so is there anyway to solve this problem so that i can input 0000-0999?
Loading
AlanPosted Oct 19, 2007, 10:11 AM
Yes, it's possible to restrict input to exactly 4 digits (including leading zeros) using code like the following:
using System;
using System.Text;
class Sample
{
static void Main()
{
Console.Clear();
Console.Write("Enter 4 digit Id : ");
string idString = GetFourDigitInteger();
int id = int.Parse(idString);
Console.WriteLine("\n\nThe Id entered was {0}", id);
Console.ReadKey();
}
public static string GetFourDigitInteger()
{
StringBuilder sb = new StringBuilder();
char key;
// only permit exactly 4 digits
do
{
while ((key = Console.ReadKey(true).KeyChar) != '\r') // return
{
if (key == '\b' && sb.Length > 0) // backspace
{
Console.Write(key + " " + key);
sb = sb.Remove(sb.Length - 1, 1);
}
else if (sb.Length == 4) / / 4 digits imput already
{
Console.Beep();
}
else if (Char.IsDigit(key)) // otherwise any digit is OK
{
Console.Write(key);
sb = sb.Append(key);
}
}
if (sb.Length < 4) Console.Beep(); // can't exit until 4 digits input
}
while(sb.Length < 4);
return sb.ToString();
}
}