Link to home
Start Free TrialLog in
Avatar of Paul_ATL
Paul_ATL

asked on

JAVA Coding: Strings and Loops

Hello, I am still new to the Java programming language and am having an issue with a code I have written. If possible, I would like some help with identifying why my code is not working for all instances.

The problem is the following:
Count the number of "xx" in the given string. We'll say that overlapping is allowed, so "xxx" contains 2 "xx".

countXX("abcxx") ¿ 1
countXX("xxx") ¿ 2
countXX("xxxx") ¿ 3

This is my code that I have written:

int countXX(String str) {
  String check = "xx";
  int count = 0;
  for (int i = 0; i < str.length(); i++){
    if (str.substring(i, i+1).equals(check)){
      count++;
    }
    else count = count;
  }
  return count;
}


My code so far only returns 0 as the answer. Thank you for any help you can provide.
SOLUTION
Avatar of CPColin
CPColin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Paul_ATL
Paul_ATL

ASKER

When I change the str.substring length to (i, i+2), I get Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: n (line number:5) for all tests except where the string is empty where n varies depending on the string values.
ASKER CERTIFIED SOLUTION
Avatar of krakatoa
krakatoa
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Something less complicated might be :
 
class FindString {

static String searchstring = new String("xxxxxxxx");
static String keystring = "xx";
static int counter =0;

public static void main(String[] args){


while(searchstring.indexOf(keystring,counter)>-1){

counter++;

}
System.out.println(counter);

}


}

Open in new window

When I change the str.substring length to (i, i+2), I get Exception:java.lang.StringIndexOutOfBoundsException.

Right. Like I said, you need to end your loop one iteration sooner. That is, "i + 1" has to be less than the length of the string, instead of what you have now.
The code I posted previously was incorrect. I think this should work :

class FindString {

static String searchstring = new String("xxxxxyyxxxx");
static String keystring = "xxx";
static int counter =0;
static int found=0;
public static void main(String[] args){

	while(counter<=(searchstring.length()-keystring.length())){
		if(searchstring.regionMatches(false, counter, keystring,0,keystring.length())){
		found++;
		}
		counter++;
	}

System.out.println(found);
}


}

Open in new window