'CodingBat - Java - String-1 "hasBad"
I hope all is well. I'm working on an algorithm in Coding Bat. I nearly have the solution at a 100%, but I have a "StringIndexOutofBoundsException" for one instance. I've given it a solid day, but I'm no closer to getting that last bit. I was wondering if someone could lend some insight.
Here's the stated problem:
*Given a string, return true if "bad" appears starting at index 0 or 1 in the string, such as with "badxxx" or "xbadxx" but not "xxbadxx". The string may be any length, including 0. Note: use .equals() to compare 2 strings.
hasBad("badxx") → true
hasBad("xbadxx") → true
hasBad("xxbadxx") → false*
Here's my code:
public boolean hasBad(String str) {
if ( str.length() >= 3 && str.substring(0, 3).equals("bad") ) {
return true;
}
if ( str.length() >= 3 && str.substring(1, 4).equals("bad") ) {
return true;
}
if ( str.length() < 3 ) {
return false;
}
return false;
}
Here are the results:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

