Reputation: 11
I have a question that asks the user to enter a student number, how can I make it so it will only accept a 5 digit number. The input is being added to an object like
console.writeline("Enter the student number: ");
then
studentObject.StudentNumber = int.Parse(Console.Readline());
I've tried using
if (Console.ReadLine().Length != 5)
{
//Do this
}
else
{
//Do this
}
But it won't work, the .Length says can't convert type int to bool. I'm stuck, any help please?
Upvotes: 1
Views: 5486
Reputation: 1
char[] cc = Console.Read().ToString().ToCharArray();
if (char.IsDigit(cc[0])&&
char.IsDigit(cc[1])&&
char.IsDigit(cc[2])&&
char.IsDigit(cc[3])&&
char.IsDigit(cc[4]))
{
//Life's GOOD!
}else { //bad input}
Note: I'm self-taught & don't have much knowledge. Correct me if wrong.
Upvotes: 0
Reputation: 186748
You can use regular expressions:
String input;
do {
Console.WriteLine("Please enter student number:");
input = Console.ReadLine();
}
while (!Regex.IsMatch(input, @"^\d{5}$")); // <- five digits expected
// input contains 5 digit string
int number = int.Parse(number);
P.S. In case that the input should be "five digit number, not starting with zero" the regular expression has to be changed to something like that:
while (!Regex.IsMatch("12345", @"^[1-9]\d{4}$")); // five digits, not zero-starting
Upvotes: 3
Reputation: 136
var input = Console.ReadLine();
int i;
if (input.Length > 0 && input.Length < 6 && Int32.TryParse(input, out i))
// i has 5 digit;
else
// i has zero
Upvotes: 0
Reputation: 6132
Probably not the answer to your question, however one thing I noticed:
if you are using Console.Readline()
in your if-statement and then want to store it in the studentObject you will need to store it in a variable first. Calling Console.Readline();
again to store it in the studentObject will cause another input to be expected, which nullifies your attempt to validate the input.
Something like this:
static void Main(string[] args)
{
Console.WriteLine("Please enter student number:");
//get the user input
var number = Console.ReadLine();
if (number.Length != 5)
{
Console.WriteLine("Invalid format.");
}
else
{
Console.WriteLine("Yay it works");
}
Console.ReadLine();
}
Upvotes: 0