Basically, I have a task that requires me to write a method called stutter. It is assumed that the stuttering method takes an input string s and returns a string with each character repeated. For example, if the input string was "help", then the result of running this method should be "hheellpp". I tried a bunch of different things and can't make it 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. This is mistake:
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)
. . , Stutter, . , , , .