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();
}
}
}
}
Here I need to print how many words entered by the user contain the substring ‘Stir.’ However I’m not sure how to get this to work, or if I’ve done any of it right in the first place!
Thanks for any help!
In your code, the line:
Enter a word longer than 4 characters, and press q to quitwill be printed twice on each iteration. Plus, you are using a wrong function to check if the string contains a sub-string. Some of yourif-elsestatements needed to be changed. Here is a better version of your code:Note that in this case you are stuck in an infinite while loop. In order to really “quit” when entering
q, you shouldbreakand get out from thewhile.