Write a recursive method stringReverse that takes a character array containing a
ID: 3556657 • Letter: W
Question
Write a recursive method stringReverse that takes a character array containing a string as an argument and prints the string backward. [Hint: Using String method toCharArray, which takes no arguments, to get a char array containing the characters in the String.]
Here is the template
import java.util.Scanner;
public class Reverse {
// call helper function
public static void stringReverse( char[] array ) {
stringReverseHelper( array, 0 );
System.out.println();
}
// print out an array of chars in reverse order
private static void stringReverseHelper( char[] array, int index ) {
// code goes here
Explanation / Answer
import java.util.Scanner;
public class Reverse {
// call helper function
public static void stringReverse( char[] array ) {
stringReverseHelper( array, 0 );
System.out.println();
}
// print out an array of chars in reverse order
private static void stringReverseHelper( char[] array, int index ) {
if(index == array.length) return;
stringReverseHelper(array, index + 1);
System.out.print(array[index]);
}
// takes user-input string and prints it reversed
public static void main( String args[] ) {
System.out.print( "Enter a string: " );
Scanner scanner = new Scanner( System.in );
String input = scanner.nextLine();
stringReverse(input.toCharArray());
// code goes here
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.