2017-08-17 31 views
-1

我有應該從用戶得到一個字符串的輸入和驗證的4件事的方法:方法不會返回更新後的字符串

,它只有1個字,不包含空格,沒有按不包含數字,並且不是空白/按下回車鍵。

如果發生任何這些問題,則會打印錯誤消息,並再次調用該方法以重新提示用戶輸入。如果字符串符合要求,則返回String。

在大多數情況下,該方法按預期工作,但是,如果我第一次輸入不正確的repsonse,那麼即使它提示錯誤並輸入正確的響應,它也會返回我第一次輸入的錯誤響應。有人可以解釋爲什麼會發生這種情況嗎?

public static String getName() { 

    //Prompt User for Name and Store it as the tmp String 
    System.out.print("Please enter the target string here: "); 
    String tmp = in.nextLine(); 

    //Check to see if the string is blank, contains more than one word, or contains numbers. If so, give error and re-prompt 
    if(tmp.equals("") || tmp.contains(" ") || tmp.contains("1") || tmp.contains("2") || tmp.contains("3") || tmp.contains("4") 
    || tmp.contains("5") || tmp.contains("6") || tmp.contains("7") || tmp.contains("8") || tmp.contains("9") || tmp.contains("0")) { 
     System.out.println("\nYou entered an invalid response, please try again\n"); 
     getName(); 
    } 

    //Return the String 
    return tmp; 
} 

回答

4

您必須指定字符串:

tmp = getName(); 
+1

此。也會建議@oznomal查看模式匹配的正則表達式。 – Kon