Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a definition for two recursive methods. public static String filter(String

ID: 3641461 • Letter: W

Question

Write a definition for two recursivemethods.

public static String filter(String s, String rem) to return a String that is the result of removing every occurrence of all of the characters in the second parameter from the first parameter. For example, filter("abcdbdabdcbddda","bd") should return the String "acaca".

public static String reverse(String s) to return a string which is the same characters as s, but in reverse order.


Write a main method to input a string from the user, then input a String of characters to remove, then print out the result of calling remove with those, as well a the original string reversed, then repeat as the user wishes.

Hint: If
s

is a String,


s.substring(1)

is all but the first character of

s

 

The code must be completed how i asked to get full points. The code must include a comment for each method describing the method, a comment for each parameter describing what the parameter represents, and a comment for each variable declaration (including instance variables) describing what the variable represents.

Explanation / Answer

import java.util.Scanner; class strings { static Scanner scan = new Scanner(System.in); public static String filter(String s, String rem) { if(s.length()==1) //the base case, the one we return from { return s; } if(rem.contains(s.substring(0, 1))) // if this occurs we have to remove the first letter in the string s and look in all the string { return filter(s.substring(1),rem); } else //return our first char in s and look in the rest of the string { return s.charAt(0) + filter(s.substring(1),rem); } } public static String reverse(String s) { if (s.length() == 1) // the base case { return s; } //take the last char and put it at the start of the string and call the reverse function for the rest of the string return s.charAt(s.length()-1)+reverse(s.substring(0, s.length() -1));//substring startindex and endindex used to get the part of the string we want } public static void main(String[]args) { String usr; String usrRemove; String reps; do { System.out.println("Please enter a string"); usr = scan.next(); System.out.println("Please enter a some letters to remove from the string: " + usr); usrRemove = scan.next(); System.out.println("The string after removal is: " + filter(usr,usrRemove)); System.out.println("The string reversed: " + reverse(usr)); System.out.println("Try again? yes/no"); reps = scan.next(); if(reps.startsWith("n")||reps.startsWith("N")) { System.out.println("Exiting"); break; } }while(true); System.exit(0); } } Hope this helps you understand.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote