Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Names Starting with Letter B | Methods
Java Extended

book
Challenge: Names Starting with Letter B

Task

Swipe to start coding

Your task is to write a sortNamesStartWithLetterB method that will return only the names from this array names that starts with the letter B.

  1. Loop through the array and count how many names start with the letter B.
  2. Use the charAt() method to extract the first letter of each name and compare it to the letter B.
  3. Make sure you are checking for the uppercase letter 'B'.
  4. After counting, set the size for the new result array.
  5. Initialize the index variable, which will be used as the index for the result array.
  6. Loop through the array again and add names starting with B to the new array.
  7. Increment the index each time you add an element to the new array.
  8. Return the new array with the names.
  9. In the main method, call the sortNamesStartWithLetterB method.

Solution

java

solution

package com.example;

public class Main {
static String[] sortNamesStartWithLetterB(String[] names) {
int size = 0;
for (String name : names) {
if (name.charAt(0) == 'B') {
size++;
}
}
String[] result = new String[size];
int index = 0;
for (String name : names) {
if (name.charAt(0) == 'B') {
result[index] = name;
index++;
}
}
return result;
}

public static void main(String[] args) {
String[] names = {"Ben", "Bob", "Alice", "Mikel", "Brian", "Brandon", "Nick", "Ryan"};
String[] namesStartsLetterB = sortNamesStartWithLetterB(names);
for (String name : namesStartsLetterB) {
System.out.print(name + " ");
}
}
}

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 3
package com.example;

public class Main {
static String[] sortNamesStartWithLetterB(String[] names) {
int size = 0;
for (String name : names) {
if (name.charAt(___) == '___') {
size++;
}
}
String[] result = new String[___];
int index = ___;
for (String name : names) {
if (name.charAt(___) == '___') {
result[___] = name;
index++;
}
}
return ___;
}

public static void main(String[] args) {
String[] names = {"Ben", "Bob", "Alice", "Mikel", "Brian", "Brandon", "Nick", "Ryan"};
String[] namesStartsLetterB = ___;
for (String name : namesStartsLetterB) {
System.out.print(name + " ");
}
}
}

Ask AI

expand
ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt