Counting substring, while loop
Posted
by
user1554786
on Stack Overflow
See other posts from Stack Overflow
or by user1554786
Published on 2012-11-21T22:56:28Z
Indexed on
2012/11/21
22:59 UTC
Read the original article
Hit count: 148
java
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!
© Stack Overflow or respective owner