Reputation: 51
Here is the main:
public class MiscStringOperationsDriver
{
public static void main(String[] args)
{
// Test the wordCount method
int numWords = MiscStringOperations.wordCount("There are five words here.");
System.out.printf("Number of words: %d\n\n", numWords);
// Test the arrayToString method
char[] letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
String lettersToString = MiscStringOperations.arrayToString(letters);
System.out.printf("The string is: %s\n\n", lettersToString);
// Test the mostFrequent method
char mostFrequentChar = MiscStringOperations.mostFrequent("aababbcddaa");
System.out.printf("The most-frequent character is: %c\n\n", mostFrequentChar);
// Test the beginWithB method
String wordList = MiscStringOperations.beginWithB(
"Batman enjoyed some blueberries and a bacon burger in the Batmobile.");
System.out.printf("The list of words is: %s\n\n", wordList);
}
}
All of the methods are in another class. I am struggling with last method which is the beginWithB method. I have everything else working. Here's what I have so far for this method:
public static String beginWithB(String wordlist) {
String myStr = wordlist;
for(String b: myStr.split(" ")){
if(b.startsWith("b")||b.startsWith("B")){
System.out.print(b);
}
}
I am struggling to find a way to return the words that start with a "b" or "B" to the main. Any ideas? (And yes, I have to do it this way).
Upvotes: 1
Views: 2825
Reputation: 1471
Your method looks fine to me, you just need to make a string as you are returning a String. (see the code bellow)
CODE
public static String beginWithB(String wordlist) {
StringBuilder sb = new StringBuilder();
String myStr = wordlist;
for (String b : myStr.split(" ")) {
if (b.startsWith("b") || b.startsWith("B")) {
sb.append(b + " ");
}
}
return sb.toString();
}
OUTPUT
The list of words is: Batman blueberries bacon burger Batmobile.
Upvotes: 1