189k views
1 vote
Debug the recursive reverseString method, which is intended to return the input String str reversed (i.e. the same characters but in reverse order).

Use the runner class to test this method but do not write your own main method or your code will not be graded correctly.
public class U10_L2_Activity_One
{
public static String reverseString(String str)
{
if (str.length() < 0)
{
return str;
}
s = reverseString(str.substring(2)) + str.substring(0,1);
}
}
Runner's code (don't change):
import java.util.Scanner;
public class runner_U10_L2_Activity_One
{
public static void main(String[] args)
{
System.out.println("Enter string:");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("Reversed String: " + U10_L2_Activity_One.reverseString(s));
}
}

1 Answer

4 votes

Answer:

Step-by-step explanation:

The following modified code correctly uses recurssion to reverse the string that was passed as a parameter to the reverseString method. A test output using the runner class can be seen in the attached image below.

import java.util.Scanner;

class U10_L2_Activity_One {

public static String reverseString(String str) {

if (str.isEmpty()) {

return str;

}

return reverseString(str.substring(1)) + str.charAt(0);

}

}

class runner_U10_L2_Activity_One

{

public static void main(String[] args)

{

System.out.println("Enter string:");

Scanner scan = new Scanner(System.in);

String s = scan.nextLine();

System.out.println("Reversed String: " + U10_L2_Activity_One.reverseString(s));

}

}

Debug the recursive reverseString method, which is intended to return the input String-example-1
User Everyday
by
4.5k points