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();
        }
    }
}

}

在这里,我需要打印用户输入的单词中有多少包含子字符串“搅拌”。但是我不知道如何让它工作,或者我是否一开始就做对了!

谢谢你的帮助!

4

3 回答 3

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

请注意,在这种情况下,您会陷入无限的 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 回答