2016-10-03 23 views
-1

我在此問題陳述中顯示了一部分輸入代碼。我想從用戶那裏只輸入字母。在這裏,我想遍歷這個方法,直到用戶以字母輸入。 getInput是我班上的方法。在該方法中迭代,直到用戶僅以字母輸入提供輸入

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

在這裏,我想,如果用戶輸入錯誤輸入此代碼應打印信息「輸入錯誤。請輸入有效的名稱。」然後再次啓動該方法。請幫助我如何做到這一點。

+1

創建一個布爾變量,並將其設置爲false。當變量爲false時循環。如果輸入有效,請將其設置爲true。 –

+0

查找用於字母數字條目的RegEx。將ReadLine與正則表達式匹配。如果通過,請寫下「謝謝」。如果不是,請寫下「必須爲字母」,然後再次調用getInput –

+0

@DStanley請您爲我提供一些代碼。要麼我需要使用while循環?或者是其他東西。如果你可以提供我的代碼,我會感謝你。 – mac

回答

-1

像這樣(LINQ的All);不要忘記檢查的空輸入(如果用戶只需按下輸入):

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(NameOfSender) && 
     NameOfSender.All(c => char.IsLetter(c))) 
     return NameOfSender; 

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

編輯:如果你允許位字母之間(如約翰史密斯),可以使用定期expresionif

... 
    if (Regex.IsMatch(NameOfSender, @"^\p{L}+(\p{L}+)*$")) 
     return NameOfSender; 
    ... 
+0

兄弟感謝它爲我工作,但我想在這一個更多的編輯。第一次應該詢問「請輸入你的姓名,如果你想發送包裹」,但是如果用戶輸入錯誤的輸入,應該說「輸入錯誤,再次輸入姓名」。在此之後我會將此標記爲我的答案。 – mac

+0

@mac:稍作修改就可以解決問題。 –

+0

非常感謝您的支持。 – mac

0

您可以使用正則表達式來驗證用戶輸入的,是這樣的:

if(System.Text.RegularExpressions.Regex.IsMatch(input, @"[\w\s]+")) 
{ 
    ... 

應該做的伎倆

瞭解正則表達式:http://www.regular-expressions.info/tutorial.html

編輯:當然,用戶可以有在他們的名字連字符,以便正則表達式不會實際上捕獲所有有效的名稱。

0
//declare this variable in your class 
public string Name = null; 

//change the return type to void 
public void getInput(){ 
    string CheckString = null; 
    while (Name.IsNullOrEmpty()){ 
     bool IsValid = true; 
     checkString = Console.ReadLine(); 
     foreach (char c in CheckString.ToCharArray()){ 
      if (!Char.IsLetter(c)){ 
       Console.WriteLine("Wrong Input!"); 
       IsValid = false; 
       break; 
      } 
     } 
     if (IsValid){ 
      Name = CheckString; 
     } 
    } 
} 

這個循環將持續到用戶提供的文本只包含字母和當它發現這個情況是真實的,將設置變量名稱的文本用戶已給出。

1
//This regex pattern will accept alphabet only, no numbers or special chars like blank spaces 
Pattern p = Pattern.compile("[a-zA-Z]"); 

do{ 
    Console.WriteLine("Please enter your name. If you want to send the parcel: "); 
    this.NameOfSender = Console.ReadLine(); 
    boolean isOnlyAlpha = p.matcher(this.NameOfSender).matches(); 
}while(!isOnlyAlpha); 
相關問題