w3resource
Java Programming Exercies

Java String Exercises: Check whether the string 'red' and 'blue' appear in same number of times in a given string

Java String: Exercise-81 with Solution

Write a Java program to check whether the string 'red' and 'blue' appear in same number of times in a given string.

Sample Solution:

Java Code:

import java.util.*;
public class Main
{
public boolean checkSameAppearance(String stng) 
{
  int l = stng.length();
  int fat = 0;
  int bat = 0;
  for (int i = 0; i < l - 2; i++) 
  {
    String tmp = stng.substring(i, i+3);
    if (tmp.compareTo("fat") == 0)
      fat++; 
    if (tmp.compareTo("bat") == 0)
      bat++; 
  }
  if (fat == bat)
    return true;
  else
    return false;
}

public static void main (String[] args)
    {
      Main m= new Main();
      String str1 =  "bigbatfatman";
      System.out.println("The given string is: "+str1);
      System.out.println("The appearance of red and blue are same: "+m.checkSameAppearance(str1));
	  }
}

Sample Output:

The given string is: bigbatfatman
The appearance of red and blue are same: true

Flowchart:

Flowchart: Java String Exercises - Check whether the string 'red' and 'blue' appear in same number of times in a given string

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to check whether the character immediately before and after of # is same in a given string.
Next: Write a Java program to repeat every character twice in the original string.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming