2013-10-10 33 views
1

我目前正在做一個練習(在任何人發出之前不做作業),我被困在問題的最後部分。Java字符串輸出字符串限制範圍到字母表

的問題是:

Write a program which will input a String from the keyboard, output the number of 
seperate words, where a word is one or more characters seperated by spaces. Your 
program should only count words as groups of characters in the rang A..Z and a..z 

我可以做的第一部分沒有問題,你可以通過我的代碼中看到:

進口java.util.Scanner的;

public class Exercise10 { 

public static void main(String[] args) { 
    String input; 
    int counter = 0; 
    Scanner keyboard = new Scanner(System.in); 

    System.out.println("Please enter your text: "); 
    input = keyboard.nextLine(); 

    for(int i = 0; i < input.length(); i++){ 

     if(input.charAt(i) == ' '){ 
      counter++; 
      } 
    } 

    System.out.println(counter + 1); 
    keyboard.close(); 

    } 
} 

當然,這是困惑我的部分是這樣的:

Your program should only count words as groups of characters in the rang A..Z and 
a..z 

我應該在這種情況下怎麼辦?

+1

你需要查找的正則表達式 – tom

+1

你做我的方式t是錯的。計數空格與計數單詞不同。如果用戶將''字「'? – Pshemo

+0

還沒有學過正則表達式,所以我寧可不使用,直到我們被教會了,因爲我不想迷惑自己。 – user2830571

回答

2

我不會給你一個完整的答案,但這裏有兩個提示。

相反的計數空間看分割線,並通過每個元素從拆分循環:

Documentation

一旦你的String分裂,可以通過元素迭代,遍歷每個每個字符檢查元素,如果它是字母:

Hint

+0

謝謝,但正如我所說我不想現在使用正則表達式。 – user2830571

+0

@ user2830571這些解決方案都不使用正則表達式。你認爲哪部分需要一個正則表達式?一旦我知道你的假設,我就可以解釋更多。 –

+0

拆分字符串? 我看着它在oracle網站上,它提到了正則表達式... – user2830571

2

我認爲它不應該把單獨的標點符號當作單詞。所以短語one, two, three !將有3個單詞,即使!由空格分隔。

拆分空格上的字符串。對於每個令牌,檢查字符;如果其中至少有一個在範圍a..zA..Z中,則增加計數器並獲取下一個標記。

+0

謝謝,但正如我所提到的,我不想目前使用正則表達式 – user2830571

+1

沒有涉及正則表達式。你所要做的就是'phrase.split(「」)'並且你得到了令牌。 –

+0

哦,我認爲它使用正則表達式... – user2830571