1

私は現在、演習を行っています (誰かが配る前の宿題ではありません) が、質問の最後の部分で行き詰まっています。

質問は:

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

この場合、どうすればよいですか?

4

2 に答える 2

2

個々の句読点を単語と見なすべきではないと思います。したがって、スペースで区切られone, two, three !ていても、フレーズは 3 つの単語になります。!

文字列をスペースで分割します。すべてのトークンについて、文字を確認してください。それらの少なくとも 1 つが範囲内a..zまたはA..Zの場合、カウンターをインクリメントして次のトークンに到達します。

于 2013-10-10T11:46:59.533 に答える