w3resource

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


62. Contains "good" at Start

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


For more Practice: Solve these Related Problems:

  • Write a Java program to verify if the substring "good" starts at index 0 or 1 of a given string.
  • Write a Java program to check whether "good" appears at the very beginning or one character in from the start.
  • Write a Java program to detect the occurrence of "good" at positions 0 or 1 and output a boolean result.
  • Write a Java program to determine if a string’s prefix contains the word "good" within its first two positions.

Go to:


PREV : Substring from First and Last N Chars.
NEXT : First Two Chars at End.

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.