Java: Check whether a specified character is happy or not
87. Check Happy Character
Write a Java program to check whether a specified character is happy or not. A character is happy when the same character appears to its left or right in a string.
Visual Presentation:
Sample Solution:
Java Code:
import java.util.*;
// Define a class named Main
public class Main {
  
  // Method to check if 'z' is happy in the given string
  public boolean aCharacterIsHappy(String stng) {
    int l = stng.length(); // Get the length of the given string
    boolean char_happy = true; // Initialize a boolean variable to check 'z' happiness
    
    // Loop through the string to check each character
    for (int i = 0; i < l; i++) {
      if (stng.charAt(i) == 'z') { // Check if the current character is 'z'
        if (i > 0 && stng.charAt(i - 1) == 'z') {
          char_happy = true; // If the previous character is 'z', set 'z' as happy
        } else if (i < l - 1 && stng.charAt(i + 1) == 'z') {
          char_happy = true; // If the next character is 'z', set 'z' as happy
        } else {
          char_happy = false; // If 'z' does not have a neighboring 'z', set 'z' as not happy
        }
      }
    }
    return char_happy; // Return whether 'z' is happy or not
  }
  // 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 = "azzlea"; // Given input string
    // Display the given string and whether 'z' is happy in it
    System.out.println("The given string is: " + str1);
    System.out.println("Is Z happy in the string: " + m.aCharacterIsHappy(str1));
  }
}
Sample Output:
The given string is: azzlea Is z happy in the string: true The given string is: azmzlea Is z happy in the string: falses
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to determine if every occurrence of a specified character in a string has at least one identical neighbor.
 - Write a Java program to check if a given character in a string is surrounded by the same character on either side.
 - Write a Java program to verify the "happiness" of a target character by scanning its adjacent positions in the string.
 - Write a Java program to return true if all instances of a specified letter in a string have matching adjacent characters.
 
Go to:
PREV : Count Triples in String.
NEXT : Replace 'is' with 'is not'.
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.
