Java: Read a string,if the string begins with "red" or "black" return that color string, otherwise return the empty string
Write a Java program to read a string. If the string begins with "red" or "black" return that color string, otherwise return the empty string.
Visual Presentation:
Sample Solution:
Java Code:
import java.util.*;
// Define a class named Main
public class Main {
// Method to pick a color from the beginning of the string
public String pickColor(String str) {
// Check if the string starts with "red", return "red" if true
if (str.startsWith("red"))
return "red";
// Check if the string starts with "black", return "black" if true
if (str.startsWith("black"))
return "black";
else
return ""; // Return an empty string if the string doesn't start with "red" or "black"
}
// Main method to execute the program
public static void main(String[] args) {
Main m = new Main(); // Create an instance of the Main class
// Define a string to check for the color at the beginning
String str1 = "blacksea";
// Display the given string and the color it begins with using the pickColor method
System.out.println("The given string is: " + str1);
System.out.println("The string begins with the color: " + m.pickColor(str1));
}
}
Sample Output:
The given strings is: blacksea The string begins with the color: black
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to read a string and return true if it ends with a specified string of length 2.
Next: Write a Java program to read two strings append them together and return the result. If the strings are different lengths, remove characters from the beginning of longer string and make them equal length.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics