2013-10-20 114 views
0

我非常新的Java和一直在嘗試寫一些代碼,以便它會檢查接收到的輸入只有字母所以沒有特殊字符或數字可以插嘴說。讓java檢查輸入的行,看它是否只有字母。

到目前爲止,我已經得到了這個地步

System.out.println("Please enter your first name"); 
    while (!scanner.hasNext("a-z") 
    { 
    System.out.println("This is not in letters only"); 
    scanner.nextLine(); 
    } 
    String firstname = scanner.nextLine(); 
     int a = firstname.charAt(0); 

這顯然不工作,因爲它只是定義輸入只能包含字符az,我希望有一種方式來告訴它它只能包含字母,但還沒有能夠找出如何。

任何幫助,甚至一個鏈接可以理解的地方,我可以讀出正確的命令,並通過自己:)弄明白

感謝

+2

看看'Character.isLetter()'方法 – andreih

+1

http://stackoverflow.com/questions/5238491/check-if-string-contains-only-letters – Trying

回答

0

您可以使用一個簡單的正則表達式爲

System.out.println("Please enter your first name"); 
String firstname = scanner.nextLine(); // Read the first name 
while (!firstname.matches("[a-zA-Z]+")) { // Check if it has anything other than alphabets 
    System.out.println("This is not in letters only"); 
    firstname = scanner.nextLine(); // if not, ask the user to enter new first name 
} 
int a = firstname.charAt(0); // once done, use this as you wish 
+1

謝謝這麼多:)現在感覺就像我試圖用一種新的語言表達我自己,我知道我想說什麼,但找不到詞:) – Chris

0
while (scanner.hasNext()) { 
    String word = scanner.next(); 
    for (int i = 0; i < word.length; i++) { 
     if (!Character.isLetter(word.charAt(i))) { 
      // do something 
     } 
    } 
} 
+0

謝謝你的回答:) – Chris

1

你可以使用任何的以下two methods

public boolean isAlpha(String name) { 
    char[] chars = name.toCharArray(); 

    for (char c : chars) { 
     if(!Character.isLetter(c)) { 
      return false; 
     } 
    } 

    return true; 
} 

public boolean isAlpha(String name) { 
    return name.matches("[a-zA-Z]+"); 
} 
+0

謝謝你的回答:) – Chris

相關問題