Dan
Dan

Reputation: 51

How to recursively take an input string and return a string with each character repeated?

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.

Upvotes: 4

Views: 3075

Answers (7)

HWJ
HWJ

Reputation: 77

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

Upvotes: 1

son15
son15

Reputation: 133

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

Upvotes: 2

JohannisK
JohannisK

Reputation: 537

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

    }

}

Upvotes: -2

Paul C
Paul C

Reputation: 66

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

Upvotes: -1

Maroun
Maroun

Reputation: 95968

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.

Upvotes: 2

CadaverousX
CadaverousX

Reputation: 146

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

Upvotes: 1

Stephen C
Stephen C

Reputation: 718916

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.

Upvotes: 1

Related Questions