w3resource

Java: Read a string,if the string begins with "red" or "black" return that color string, otherwise return the empty string


59. Begins With Color 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:

Java String Exercises: Read a string,if the string begins with "red" or "black" return that color string, otherwise return the empty string


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:

Flowchart: Java String Exercises - Read a string,if the string begins with "red" or "black" return that color string, otherwise return the empty string



For more Practice: Solve these Related Problems:

  • Write a Java program to extract a color prefix from a string if it starts with "red" or "black" using string comparison.
  • Write a Java program to detect and return the prefix "red" or "black" from a string, otherwise returning an empty string.
  • Write a Java program to check for multiple color prefixes at the beginning of a string and return the matched prefix.
  • Write a Java program to scan a string for initial color codes ("red", "black", "blue") and output the found color.

Go to:


PREV : Ends With Specific Two Characters.
NEXT : Append Strings Equal Length.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.