w3resource

Java: Check whether a specified character is happy or not

Java String: Exercise-87 with Solution

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:

Java String Exercises: Check whether a specified character is happy or not

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:

Flowchart: Java String Exercises -Check whether a specified character is happy or not.

Java Code Editor:


Improve this sample solution and post your code through Disqus

Previous: Write a Java program to count the number of triples (characters appearing three times in a row) in a given string.
Next: Write a Java program to return a string where every appearance of the lowercase word 'is' has been replaced with 'is not'.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/string/java-string-exercise-87.php