Question

Java Program Write a recursive method that takes a string and return a string where every...

Java Program Write a recursive method that takes a string and return a string where every character appears twice.

Output must match exactly as below: only two LL's since there is already two of the character

For example, if the string is “HELLO”, it will return “HHEELLOO”.

Write a program to test it. must be recursive!!!

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.Scanner;

public class Twice {

    public static String twice(String s) {
        if(s.isEmpty()) {
            return "";
        } else {
            if(s.length() > 1 && s.charAt(0) == s.charAt(1)) {
                return s.substring(0, 2) + twice(s.substring(2));
            }
            return "" + s.charAt(0) + s.charAt(0) + twice(s.substring(1));
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a string: ");
        System.out.println(twice(in.nextLine()));
    }

}

)#xxix:x: aa :ri:,W:沺.JCKI :: HELLO HHEELLOO Process finished with exit code 0

Add a comment
Know the answer?
Add Answer to:
Java Program Write a recursive method that takes a string and return a string where every...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT