Please code in Java Write a recursive method that takes a string and return a string where every character appears twice. For example, if the string is “HELLO”, it will return “HHEELLOO”. Write a program to test it.
import java.util.Scanner; public class DoubleCharacters { public static String repeatCharacters(String s) { if (s.length() == 0) { return ""; } else if (s.length() == 1){ return s + s; } else { if (s.charAt(0) == s.charAt(1)) { return s.substring(0, 2) + repeatCharacters(s.substring(2)); } else { return "" + s.charAt(0) + s.charAt(0) + repeatCharacters(s.substring(1)); } } } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a string: "); String s = in.nextLine(); System.out.println(repeatCharacters(s)); } }
Get Answers For Free
Most questions answered within 1 hours.