Basically I have an assignment that requires me to write a method called stutter. The stutter method is supposed to take an input String s and return the string with each character repeated. For example, if the input string was "help" then the result of running this method should be "hheellpp". I have tried a bunch of different things and can't get it to work. Here is my code:
import java.util.*;
public class Stutter {
static String stutterString = "";
public static String stutter ( String s ) {
char ch = s.charAt (0);
String tempString = String.valueOf ( ch );
if ( s.length() == 0 ) {
return stutterString;
} else {
stutterString += tempString + tempString;
return stutter ( s.substring (1) );
}
}
public static void main ( String [] args ) {
Scanner inputScanner = new Scanner ( System.in );
System.out.println ( "What word would you like to stutter?" );
String userInput = inputScanner.next();
inputScanner.close();
System.out.println ( stutter ( userInput ) );
}
}
I get an error that I'm not sure what to do with. This is the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Stutter.stutter(Stutter.java:12)
at Stutter.stutter(Stutter.java:23)
at Stutter.main(Stutter.java:41)
Any help would be appreciated. This isn't a huge program. As you can see, I've posted the entire Stutter class that I'm using. It's just bugging me because I'm sure there is a simple fix to this, but I'm not seeing it.
s.length() == 0before you get to theifstatement?)