Course Content
Java Basics
1. Getting Started
Java Basics
Challenge














Task
You are given an array of strings. Your task is to output a new array of strings where each string contains the letter "b".
Main.java
- 1. First, you need to determine the
size
of your new array. Use afor-each loop
and anif statement
to check each word for the presence of the desired letter. You can check if a string contains a letter using thecontains()
method;- 2. Create a separate variable of type
int
and increase it each time you find a word with the desired letter;
- 2. Create a separate variable of type
- 3. Now, you need to create a new string array with the
size
you calculated in the first loop; - 4. Use a for-each loop and a separate variable to store the elements in the new array;
It should look something like this:
result[index] = element;
index++;
- 5. Don't forget to use an
if statement
in the second loop to check if the string contains the desired letter.
This is a challenging task. If you're having trouble, you can confidently click the solution button and analyze what's written there.
package com.example;
public class Main {
public static void main(String[] args) {
String[] input = {"ball", "programming", "combination", "winter", "probability", "chair"};
int length = 0; // creating a new int variable to calculate the length of the new array
for (String element : input) { // using for-each loop to calculate the length of the new array
if (element.contains("b")) {
length++; //incrementing our length every time we see that element of input array contains "b"
}
}
String[] result = new String[length]; //creating new string array with length that we have calculated before
int index = 0; //creating a new int variable that will be responsible for indexing in our result array
for (String element : input) { //using for-each loop to add each element that contains letter "b" from first array into second one
if (element.contains("b")) {
result[index] = element; // adding element that passes our condition
index++; //incrementing the index in our new array
}
}
for (String element : result) { //using for-each loop to output our result array
System.out.print(element + " ");
}
}
}














Everything was clear?
Section 5. Chapter 4