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

4) Write a recursive method isBackwards that has two String parameters and retur

ID: 3871606 • Letter: 4

Question

4) Write a recursive method isBackwards that has two String parameters and returns true if the two Strings have the same sequence of characters but in the opposite order (ignoring white space and capitalization), and returns false otherwise. The method should throw an IllegalArgumentException if either String is null. Test this method with following examples, isBackwards("Fried", "deirf") ->true isBackwards("Sit", "Toes") -> false isBackwards("","") ->true isBackwards("I nadam", "mad am I") -> true Hint: You may find the toLowerCase and isWhitespace methods of the Character class helpful in Java APl. public boolean isBackwards(String first, String second)

Explanation / Answer

import java.io.*;


public class DemoBackwards{

    public static boolean isBackwards(String s1, String s2){
         
          boolean res = true;
          String a,b;
          a = s1.replace(" ","");
          b = s2.replace(" ","");
          if (a.equals("") && b.equals(""))
             return true;
          if (a.length() != b.length())
              return false;
          for (int i = 0; i<a.length(); i++){
           
             if (Character.toLowerCase(a.charAt(i)) != Character.toLowerCase(b.charAt(a.length()-1-i))){
               
                return false;
             }
          }
          return res;
        
    }
    public static void main(String[] args){

        System.out.println(isBackwards("Fried","deirf"));
        System.out.println(isBackwards("Sit","Toes"));
        System.out.println(isBackwards("",""));
        System.out.println(isBackwards("I madam","mad am I"));
    }
}

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