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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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);
}
}
When I change the str.substring length to (i, i+2), I get Exception:java.lang.StringIndexOutOf BoundsExce ption.
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);
}
}
ASKER