0

私はCSファイナルのためにいくつかの演習を行っていますが、この問題に悩まされています。この問題では、文字列を読み取り、ユーザーから最小の長さを取得し、少なくともその数の文字を含む単語の量を返す必要があります。私のコードは問題ないように見えますが、答えを出力できません。誰かが私を助けることができますか?

public class WordCount {



    public static void main (String [] args) {
        System.out.println("Enter a string: "); 
        String input =  IO.readString();


        System.out.println("Enter minimum word length");
        int wordlength = IO.readInt();
        int count = 0 ;
        do  {

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

                if (input.indexOf(i) == ' ') {

                    String check = input.substring(0, i);
                    if (check.length() >= wordlength) {

                        count++;
                        input = input.substring(i);
                        break;

                    }
                }

                    }

        } while (input.length() > 0);


    System.out.print("Words longer than " + wordlength + " characters: " + count);

    }

}

whileループが無限に実行されているように見えますが、理由がわかりません。

4

5 に答える 5

3

以下のようにsplitを使用します。

    System.out.println("Enter minimum word length");
    int wordlength = IO.readInt();
    int count = 0 ;
    //get all words in string array by splitting the input around space
    String[] words = input.split(" ");//assuming words are separated by space

    //now iterate the words, check the length, if word is of desired length or more
    //increase the word counter
    for (int i = 0 ; i < words.length; i ++) {
       if (words[i].length() >= wordlength) {
         count++;
       }
    }
于 2012-12-07T21:35:05.267 に答える
2

現在、私が最初に指摘するあなたのコードに関するいくつかの問題があります:-

if (input.indexOf(i) == ' ')

上記のステートメントでは、String#charAtメソッドを使用して、特定のインデックスの文字を取得する必要があります。String#indexOfメソッドは逆のプロセスに使用されます。つまり、文字があり、そのインデックスを検索する必要があります。

次に、input内部を変更していますloop itselfinputそして、の終了条件での長さを使用していloopます。このようなことはしてはいけません。代わりに、最後に処理した単語のインデックスを格納する別の変数を使用できます。そしてそれindexをあなたのsubstring方法で使ってください。

do while第三に、ここではループは本当に必要ありません。あなたfor loop自身があなたのすべてのキャラクターを繰り返しています。を削除するだけbreakですifが、これは実際には必要ありません。

したがって、コードは次のように変更されます。-

int oldIndex = 0;  // to maintain the end index of previous word.
int length = input.length();
for (int i = 0 ; i < length; i ++) {

          if (input.charAt(i) == ' ' || i == length - 1) {

                // If the word is at the end, then probably your first 
                // condition in above `if` would fail, that is why I used a 
                // second condition, which checks the end of string

                // Now for the end of the string, we would need to use a single
                // arguement substring method to get the word till the end.
                // hence the below conditional expression.

                String check = (i == length - 1)? input.substring(oldIndex): 
                                                input.substring(oldIndex, i);

                oldIndex = i + 1;  // Set oldIndex to the next index.

                if (check.length() >= wordlength) {

                    count++;
                    //  input = input.substring(i);  Don't do this
                    // break;   // Don't break too.

                }
           }

}

これがコードの変更であり、間違いが何であったかを知ることができます。

ただし、必要なものを取得するための非常に簡単な方法があります。の文字列にString#splitmethodを使用すると、すべての単語の配列が返され、それらの単語を操作できます。splitspace

これは次のように機能します(使用できる場合):-

String[] words = input.split(" ");  // split input string on space

for (int i = 0; i < words.length; i++) {  // iterate over array
    if (words[i].length() >= wordLength) {
        count++;
    }
}

System.out.println(count);
于 2012-12-07T21:35:12.397 に答える
0

do-whileループは無期限に実行されます。これは、ループを設定したためです。これを単純化しましょう:

string input = "this is an example string";
do
{
     //some logic
     if (input.indexOf(i) == ' ') // this never executes - indexOf(i) returns an int
     {
          //do some stuff with input
     }

}
while (input.length() > 0); 

input.length()常にゼロより大きい。変更するブロックinputは実行されないためinput、同じままであり、文字列の長さinputは常に0より大きくなります。

于 2012-12-07T21:36:24.690 に答える
0

位置にある文字を取得するためindexOf(i)にを使用する必要はありませんが、ループとロジックは、指定された目的で問題ないように見えます。charAt(i)i

于 2012-12-07T21:38:09.180 に答える
0

サブストリングについてはjavadocを見てください。それはあなたがそれを与えるインデックスから始まり、包括的です。したがって、サブストリング呼び出しは常に、少なくとも1つの長さのストリングを提供します。

public String substring(int beginIndex)
Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

Examples:

     "unhappy".substring(2) returns "happy"
     "Harbison".substring(3) returns "bison"
     "emptiness".substring(9) returns "" (an empty string)


Parameters:
    beginIndex - the beginning index, inclusive. 
Returns:
    the specified substring. 
Throws:
    IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

次のようなものを試してください。

String input = "one two three four five six seven eight nine ten";
    int minLength = 4;
    int count = 0;
    String[] strings = input.split(" ");
    for(String s : strings) {
        if(s.length() >= minLength) {
            ++count;
        }
    }

    System.out.println(count);
于 2012-12-07T21:38:58.440 に答える