计算子字符串,while循环

时间:2012-11-21 22:56:29

标签: java string

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”。但是我不知道如何让它工作,或者我是否已经做好了!

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

在您的代码中,每次迭代都会打印两行Enter a word longer than 4 characters, and press q to quit。另外,您使用了错误的函数来检查字符串是否包含子字符串。您的一些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

请注意,在这种情况下,您将陷入无限循环。为了在输入q时真正“退出”,您应该break并从while退出。

答案 1 :(得分:0)

您应该使用String.contains ("Stir")代替String.substring(0,4).equals("Stir")

javadoc for String.contains所述,此方法

  

当且仅当此字符串包含指定的字符串时,才返回true   char值序列。

答案 2 :(得分:0)

String.contains("Stir")

将有助于您的情况。