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
.
- Loop through the array and count how many names start with the letter
B
. - Use the
charAt()
method to extract the first letter of each name and compare it to the letterB
. - Make sure you are checking for the uppercase letter 'B'.
- After counting, set the size for the new result array.
- Initialize the index variable, which will be used as the index for the result array.
- Loop through the array again and add names starting with
B
to the new array. - Increment the index each time you add an element to the new array.
- Return the new array with the names.
- In the main method, call the
sortNamesStartWithLetterB
method.
Solution
solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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?
Thanks for your feedback!
Section 2. Chapter 3
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
Ask anything or try one of the suggested questions to begin our chat