Write a static method named favoriteLetter that accepts two parameters : a Scann
ID: 3585183 • Letter: W
Question
Write a static method named favoriteLetter that accepts two parameters: a Scanner from the console, and a favorite letter represented as a one-letter String. The method repeatedly prompts the user until two consecutive words are entered that start with that letter. The method then prints a message showing the last word typed.
You may assume that the user will type single-word responses to each prompt. Your code should be case-sensitive, (if the favorite letter is a, you should not stop prompting if the user types words that start with a capital A.
The following represents output from two calls to your method:
(User input is underlined.)
Call
Scanner console = new Scanner(System.in);
favoriteLetter(console, "y");
Scanner console = new Scanner(System.in);
favoriteLetter(console, "A");
Output
Looking for two "y" words in a row.
Type a word: hi
Type a word: bye
Type a word: yes
Type a word: what?
Type a word: yellow
Type a word: yippee
"y" is for "yippee"
Looking for two "A" words in a row.
Type a word: I
Type a word: love
Type a word: COSC236!
Type a word: AND
Type a word: PROGRAMS
Type a word: are
Type a word: always
Type a word: Absolutely
Type a word: Awesome
"A" is for "Awesome
Call
Scanner console = new Scanner(System.in);
favoriteLetter(console, "y");
Scanner console = new Scanner(System.in);
favoriteLetter(console, "A");
Output
Looking for two "y" words in a row.
Type a word: hi
Type a word: bye
Type a word: yes
Type a word: what?
Type a word: yellow
Type a word: yippee
"y" is for "yippee"
Looking for two "A" words in a row.
Type a word: I
Type a word: love
Type a word: COSC236!
Type a word: AND
Type a word: PROGRAMS
Type a word: are
Type a word: always
Type a word: Absolutely
Type a word: Awesome
"A" is for "Awesome
Explanation / Answer
public static void favoriteLetter(Scanner console, String letter)
{
System.out.println("Looking for two "" + letter + "" words.");
int count = 0;
String word = "";
while (count < 2)
{
System.out.print("Please enter a word: ");
word = console.next();
if (word.startsWith(letter)) {
count++;
} else {
count = 0;
}
}
System.out.println(""" + letter + "" is for "" + word + """);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.