0
public class SubstringCount
{
     public static void main(String[] args)
    { 
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a word longer than 4 characters, and press q to quit");
    int count = 0;


    while (scan.hasNextLine())
    {
        System.out.println("Enter a word longer than 4 characters, and press q to quit");
        String word = scan.next();

        if (word.substring(0,4).equals("Stir"))
        {
            count++;
            System.out.println("Enter a word longer than 4 characters, and press q to quit");
            scan.next();
        }

        else if (word.equals("q"))
        {
            System.out.println("You have " + count + ("words with 'Stir' in them"));
        }

        else if (!word.substring(0,4).equals("Stir")) 
        {
            System.out.println("Enter a word longer than 4 characters, and press q to quit");
            scan.next();
        }
    }
}

}

ここでは、ユーザーが入力した単語の数に部分文字列「Stir」が含まれていることを出力する必要があります。ただし、これを機能させる方法がわかりません。または、そもそもこれを正しく実行したかどうかもわかりません。

助けてくれてありがとう!

4

3 に答える 3

1

コードでは、行:Enter a word longer than 4 characters, and press q to quitが各反復で 2 回出力されます。さらに、文字列に部分文字列が含まれているかどうかを確認するために間違った関数を使用しています。ステートメントの一部をif-else変更する必要がありました。コードのより良いバージョンは次のとおりです。

import java.util.Scanner;

    public class SubstringCount
    {
         public static void main(String[] args)
         { 
             Scanner scan = new Scanner(System.in);
             System.out.println("Enter a word longer than 4 characters, and press q to quit");
             int count = 0;
             while (scan.hasNextLine())
             {
                String word = scan.next();
                if (word.contains("Stir"))
                {
                  System.out.println("Enter a word longer than 4 characters, and press q to quit");
                  count++;
                }
                else if (word.equals("q"))
                {
                  System.out.println("You have " + count + ( "words with 'Stir' in them"));
                  System.out.println("Enter a word longer than 4 characters, and press q to quit");
                }   
                else
                {
                  System.out.println("Enter a word longer than 4 characters, and press q to quit");
                }
             } //end of while
        }      //end of main
    }          //end of class

この場合、無限 while ループに陥っていることに注意してください。に入るときに本当に「やめる」ためには、 から出るq必要があります。breakwhile

于 2012-11-21T23:04:56.183 に答える
0

String.contains ("Stir")代わりに使用する必要がありますString.substring(0,4).equals("Stir")

String.containsのjavadocには状態が含まれているため、このメソッドは

この文字列に指定されたchar値のシーケンスが含まれている場合にのみtrueを返します。

于 2012-11-21T22:57:33.107 に答える
0

String.contains("Stir")

あなたの場合に役立ちます。

于 2012-11-21T22:59:17.647 に答える