w3resource

Java: Read a string and return true if "good" appears starting at index 0 or 1 in the given string

Java String: Exercise-62 with Solution

Write a Java program to read a string and return true if "good" appears starting at index 0 or 1 in the given string.

Visual Presentation:

Java String Exercises: Read a string and return true if "good" appears starting at index 0 or 1 in the given string

Sample Solution:

Java Code:

import java.util.*;

// Define a class named Main
public class Main {

    // Method to check if the string contains 'good' either at the beginning or after the first character
    public boolean hasGood(String str) {
        if (str.length() < 4) // If the string length is less than 4, return false
            return false;
        else if ((str.substring(0, 4)).equals("good")) // If the substring from index 0 to 4 matches "good", return true
            return true;
        else if (str.length() > 4) { // If the string length is greater than 4
            if ((str.substring(1, 5)).equals("good")) // If the substring from index 1 to 5 matches "good", return true
                return true;
        }
        return false; // Return false if none of the conditions are met
    }

    // Main method to execute the program
    public static void main(String[] args) {
        Main m = new Main(); // Create an instance of the Main class

        String str1 = "goodboy"; // Input string

        // Display the given string and whether 'good' appears in the string using hasGood method
        System.out.println("The given strings is: " + str1);
        System.out.println("The 'good' appears in the string: " + m.hasGood(str1));
    }
}

Sample Output:

The given strings is: goodboy
The 'good' appear in the string is: true

Flowchart:

Flowchart: Java String Exercises - Read a string and return true if "good" appears starting at index 0 or 1 in the given string

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to create a new string taking specified number of characters from first and last position of a given string.
Next: Write a Java program to check whether the first two characters present at the end of a given string.

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.