4

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.

3
  • 3
    Have you tried debugging or adding logging to work out what's going wrong? What have you discovered so far? How much do you understand about the exception? (Hint: you're recursing with a shorter and shorter string each time. What happens when s.length() == 0 before you get to the if statement?) Commented Apr 24, 2015 at 10:26
  • May be you could think which is the value of the argument given to stutter. On the other hand, is it mandatory to do it recursively? If it is not you could think in an iterative version of the method introducing a loop. Commented Apr 24, 2015 at 10:30
  • Yes it was mandatory that it be recursive. And I have tried to use the debugger, but I'm only in 2nd year Comp Sci classes, so we haven't gotten into the debugger much. I'm not really sure how to use it. Thank you guys for the suggestions though. I was able to figure it out with all the help. Commented Apr 24, 2015 at 18:33

7 Answers 7

2

You need to change this line

char ch = s.charAt (0);

to

char ch = s.length() > 0 ? s.charAt(0) : ' ';

And your code will work as expected.

A better and clearer solution would be:

if (s.length() == 0) {
    return stutterString;
} else {
    char ch = s.charAt(0);
    String tempString = String.valueOf(ch);
    stutterString += tempString + tempString;
    return stutter(s.substring (1));
}

What word would you like to stutter?
>> abcdefg
>> aabbccddeeffgg

Explanation:

What will happen when you try to s.charAt(0) when s is an empty String? You're not verifying that s is not empty, adding the simple check s.length() > 0 is what you're missing.

Tip: Always use the debugger, it's there to help you, you'll better understand the flow of your program when you use it. Also when writing a recursion, using a pencil and a paper to draw the calls will help you to understand it.

Sign up to request clarification or add additional context in comments.

2 Comments

I knew it was something fairly simple. I'm still pretty new to eclipse and programming in general. I'm only in like 2nd year college Computer Science classes, and sometimes programming can be tricky. I just wasn't looking at it from the right perspective. Thanks so much for the help though. Both of your suggestions solved my problem, but I went with the 2nd suggestion, putting the lines where I declare and initialize ch and tempString inside the else block. It did seem like the better solution. Thanks again!
I'm glad it helped you. That's fine.. All programmes do mistakes, don't feel bad about it.. and you're welcome :)
2

I did it like this:

My base case is when the length of the string is less than 1, in which case it will return "".

Otherwise it will print of the first character of the string twice, and then call the stutter method again.

I pass in the original string as a parameter, except I have removed the first character from it.In this way the 2nd character of the original string will be printed out twice next and the string gets shorter.

import java.util.*;

public class Stutter {  

    public static String stutter ( String s ) {
        if(s.length() < 1) return "";
        else{
            return "" + s.charAt(0) + s.charAt(0) + stutter(s.substring(1,s.length()));
        }
    }

    public static void main ( String [] args ) {
        Scanner s = new Scanner ( System.in );
        System.out.println ( "What word would you like to stutter?" );
        String userInput = s.nextLine();
        System.out.println(stutter(userInput));
    }
}

5 Comments

Care to explain please.
THe base case for the method is if the string length is < 1, in which case it will return "". Otherwise it will print the first char of the string twice and then call the stutter method again. In the stutter method I pass in the same string as a parameter except I started at 1 as opposed to zero.
Upvote for recursing properly, even though this answer is missing an explanation of what causes OP's error. The explanation of the program could also be in the answer itself, rather than in a comment.
Yeah sorry, I'm new to this site :)
Thanks for the suggestion. It seems like your code would work, but I used Maroun's suggestion which only had me move two lines of code inside my else block. Thanks again though. I appreciate the help.
1

Hint: if s.length() is zero, then s.charAt(0) will throw an exception ... because you are trying to fetch a character beyond the end of the zero-length string.

1 Comment

Thanks for the hint! I'm in like 2nd year Computer Science classes in college, so I'm still learning how to program. Sometimes it can be tricky. Thanks again.
1

Check the length of your s variable before s.charAt (0). For example, move

char ch = s.charAt (0);
String tempString = String.valueOf ( ch );

to else block

1 Comment

This is exactly what Maroun's answer suggested as well. I moved those two lines of my code to the else block and it worked. Thanks for the suggestion. I appreciate the help.
1

How about this:

public class Stutter {
    private static String head(String str) {
        return str.substring(0,1);
    }

    private static String tail(String str) {
        return str.substring(1);
    }

    private static String stutter(String str) {
        if (str.length() > 0)
            return head(str)+head(str)+stutter(tail(str));
        else
            return "";
    }

    public static void main(String args[]) throws Exception  {
        if (args.length > 0) {
            System.out.println(stutter(args[0]));
        }
    }
}

Comments

-1

This can be achieved very simply using String.replaceAll():

public class Stutter {
    public static void main (String args[]) {
        String TEST_STRING = "abcdefg";
        System.out.println(stutter(TEST_STRING));
    }

    private static String stutter(String s) {
        return s.replaceAll("(.)", "$1$1");
    }
}

3 Comments

This is a different solution. Will not help OP understanding his actual problem.
In my opinion the problem is that the OP is trying to reinvent the wheel when there's a perfectly good Java SE API for the job.
I think OP is trying to understand recursion.
-2

Editted.

import java.util.*;

public class Stutter {

    static String stutterString = "";

    public static String stutter ( String s ) {
        if(s.length() > 0)
        {
            return stutterString.concat(s.substring(0,1)).concat(s.substring(0,1)).concat(stutter(s.substring(1)));
        }
        else
        {
            return stutterString;
        }
    }

    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 ) );

    }

}

2 Comments

This is a different solution. Will not help OP understanding his actual problem.
There is very little recursing going on here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.