0

私の目標は、文字列を受け入れるコードと、各単語に許可される最小文字数を作成することです。出力は、ユーザーが入力した最小値以上の文の単語数をユーザーに伝える int になります。

これに対する私のアプローチは、メイン メソッドで文を個々の単語に分割し、それらの各単語を文字数をカウントする別のメソッドに送信することでした。

主な方法、特に文を個々の単語に分割するのに問題があります。配列を使用せずに、ループ、部分文字列、indexOf などのみを使用してこれを実現したいと考えています。問題が発生しているコードのセクションにコメントしました。単語が 1 つだけの文字列を使用して残りのコードをテストしたところ、letterCount メソッドは正常に動作しているようです。答えはおそらく簡単だと思いますが、まだそれを理解するのに苦労しています.

どんな助けでも素晴らしいでしょう!ありがとうございました!

これが私のコードです:

public class Counter
{
public static void main(String [] args)
{
    int finalcount = 0;

    System.out.print("Enter your string: ");
    String userSentence = IO.readString();


    System.out.print("Enter the minimum word length: ");
    int min = IO.readInt();

    //Error checking for a min less than 1

    while(min < 0)
    {
        IO.reportBadInput();
        System.out.print("Enter the minimum word length: ");
        min = IO.readInt();
    }


    int length = userSentence.length(); // this will get the length of the string



    for(int i = 0; i < length; i ++)
    {
         if (userSentence.charAt(i) == ' ')
         {  

             /* I dont know what to put here to split the words!

                  once I split the userSentence and store the split word into
                  a variable called word, i would continue with this code: */

            if((letterCounter(word)) >= min)
                finalcount++;

            else
                finalcount = finalcount;

           }
    }       




    IO.outputIntAnswer(finalcount);

}

//this method counts the number of letters in each word

    public static int letterCounter (String n)
        int length = n.length(); 
        int lettercount= 0;


     for(int i = 0; i < length; i ++)

    {
        boolean isLetter = Character.isLetter(n.charAt(i));

         if (isLetter) 
         {
            if ((n.length()) >= length) 
            {
                lettercount++;
            }
         }

    }

    return lettercount;
 }

}

4

2 に答える 2

0

これを実現するには、次のように string.split() を使用できます。

String [] splittedString  = inputString.split(" ");

for(int i = 0;i< splittedString.length; i++){
    String currentWord = splittedString[i];

    if(currentWord.length() >= min){
        finalcount++;
    }
}
于 2013-10-29T15:48:28.907 に答える