mac mac - 1 month ago 12
C# Question

iterate in the method until user provides input in alphabets only

I am showing a part of my input code in this problem statement. I want to get the input in only alphabets from the user. Here I want to iterate through this method until the user provide input in alphabets. getInput is the method in my class.

public string getInput() {


Console.WriteLine("Please enter your name. If you want to send the parcel: ");
this.NameOfSender = Console.ReadLine();
return NameOfSender;
}


Here I want that If user enter wrong input this code should print message "Wrong Input. Please enter valid name." and then goto start of the method again. Please help me how to do that.

Answer

Something like this (Linq All); do not forget check for an empty input (if user just pressed enter):

public string getInput() {
  Console.WriteLine("Please enter your name. If you want to send the parcel: ");

  while (true) {
    NameOfSender = Console.ReadLine();

    // if name is 
    //   1. Not empty
    //   2. Contains letters only
    // then return it; otherwise keep asking 
    if (!string.IsNullOrEmpty(this.NameOfSender) && 
         NameOfSender.All(c => char.IsLetter(c))) 
      return NameOfSender;

    Console.WriteLine("Wrong input. Enter name again");
  } 
} 
Comments