. Advertisement .
..3..
. Advertisement .
..4..
Here is the program I run:
public boolean catDog(String str)
{
int catAnswer = 0;
int dogAnswer = 0;
int cat_Count = 0;
int dog_Count = 0;
for (int i=0; i< str.length()-1; i++)
{
String sub = str.substring(i, i+2);
if ((sub.equals("cat"))) cat_Count++;
if ((sub.equals("dog"))) dog_Count++;
catAnswer = cat_Count;
dogAnswer = dog_Count;
} //end for
if(dogAnswer == catAnswer ) {return true;}
// else
return (dogAnswer != catAnswer);
}
After I run, it returns an error:
Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 7 (line number:10) - hence i use i + 2 (no errors are reported with it
Does anyone have any suggestions for the problem below: return true if the string “cat” and “dog” appear the same number of times in the given string in the java – How to correct it?
The cause: Run time exception is to blame for the error. StringIndexOutOfBoundsException is issued because you are accessing the element at a position that is bigger than its length.
Solution: Using split is “all correct” answer for the error: return true if the string “cat” and “dog” appear the same number of times in the given string. To retain trailing empty strings, use the -1.
Although you’re close to finding a solution, there are some critical issues in your code.
A string of
2
is returned bysubstring()
when you callsubstring()
. This string cannot ever becat
ordog
. To get3
characters, change the second parameter of the method calli + 3
.Calling
substring()
will result inIndexOutOfRangeException
asi
nears the end of the input string. You should not ask for substrings that exceed the length of your input string. This bug can be fixed by changing thefor
conditional expression toi < str.length() - 2
.Your method’s return value will always be
true
. IfdogAnswer != catAnswer
is used, you will return the exact same expression. This will resolve totrue
. One solution is to merge thereturn
statements intoreturn dogAnswer == catAnswer
.There are also a few things that you can do to make your code easier:
It is not necessary to convert
cat_Count
intocatAnswer
ordog_Count
intodogAnswer
. You can discard two variables and only use one pair.Your loop can only be optimized to consider the third position of the input string if it is restricted to
cat
ordog
. Changei++
intoi += 3
.(Update: After reviewing the test data at
CodingBat
(I can assure you that this isn’t the case.
After I had implemented fix #1, #2, and #3, as well as suggestion 1, I ran a test using the test bench. The result was quite satisfying.
All right