Checking that all occurrences of 'g' have another 'g' as a neighbor We'll say that a lowercase 'g' in a string is "happy" if there is another 'g' immediately to its left or right. Return true if all the g's in the given string are happy.

gHappy("xxggxx") → true
gHappy("xxgxx") → false
gHappy("xxggyygxx") → false



This is my code so far, which I think is very messy.

  public boolean gHappy(String str) 
  {
        for(int i=1;i&lt;str.length()-1;i++)
           {
              if(str.charAt(i)=='g')
                 if(str.charAt(i-1)!='g'&amp;&amp;str.charAt(i+1)!='g')
                    return false;
  }                   
  if(str.length()==1)
      return false;
  if(str.equals(""))
      return true;
if(str.charAt(str.length()-1)=='g')
      if(str.charAt(str.length()-2)!='g')
        return false;

  return true;
}
Other answers have good input on a number of factors I agree with, especially about the early-return logic, the bugs that were pointed out, and the bracing strategies.

My suggestion though, is to use a different (the right?) tool for the job.

Regular expressions are a tool that are designed for text processing, and a well-crafted expression is typically faster and more concise than the hand-coded alternative. Regular expressions are not always the solution, but in this case, the result would be simpler to read (for someone familiar with them).

In this case, the logic requires checking that all 'g' chars are happy for the check to return true. Alternatively, to make sure there are no unhappy 'g' chars.

The expression to check for unhappy 'g' chars will be:

 private static final Pattern UNHAPPYG = Pattern.compile("(?&lt;!g)g(?!g)");


That expression says "Match any 'g' that has no 'g' before it, and no 'g' after it.

Then, you can use it as:

private static final boolean gHappy(String str) {
    return !UNHAPPYG.matcher(str).find();
}


I have put together an Ideone example here.