0

First time poster and a programming newbie so go easy on me! Just working on a little challenge given to me that required a method to check if a substring (aSub) could be found within a string (aString). This is what I wrote but it always returns false unless aSub == aString, then it will return true. I'm sure this will be a facepalm to a lot of you but I lack the experience to see exactly where the fault is! Thanks guys!

/**
 * 
 */
public boolean stringChecker(String aString, String aSub)
{
   boolean foundIt = false;
   int beginIndex = 0;
   int endIndex = aSub.length();

   while((foundIt == false) && (endIndex <= aString.length()))
   {
      if(aSub != aString.substring(beginIndex, endIndex))
      {
         beginIndex = beginIndex + 1;
         endIndex = endIndex + 1;
      }
      else
      {
         foundIt = true;
      }
   }
   return foundIt;
}
  • There's a good chance this is because when comparing strings in Java you should use .equals() and not == but I can't test to be sure right now. – Erik Jan 21 '16 at 12:25
  • 1
    Also, please don't use `foundIt == false`, since this is error prone for programming newbies (they often write `foundIt = false` instead). Use `!foundIt` instead. And read this about the [negation operator](http://kodejava.org/how-do-i-use-the-boolean-negation-operator-in-java/). – Tom Jan 21 '16 at 12:28
  • 1
    Thanks all you guys! I was up all night thinking about it and you solved it in seconds! Looks like I've got a long way to go! – giorgioscia Jan 21 '16 at 13:06
  • Well, there are a lot of new users who asks about with their String comparison, so we are kind of experienced in handling it :D. – Tom Jan 21 '16 at 14:06

0 Answers0