In: Computer Science
This is a homework question. It has to be done using JAVA language. And PAY ATTENTION TO WHAT YOU CAN USE AND WHAT I SPECIFICALLY ADDED THAT CANT BE USED TO COMPLETE THIS.
Objective:
Write a program that takes in two words, and then it recursively determines if the letters of the first word are contained, in any order, in the second word. If the size of the first word is larger than the second then it should automatically return false. Also if both strings are empty then return true.
You May NOT: ******************************************************************************************
Use any iterative loops. In other words, no for-loops, no while-loops, no do-while-loops, no for-each loops.
Use the string method .contains(String)
You May: ******************************************************************************************
Use the string method .charAt(Index)
Hints:
Recursive methods generally attempt to solve a smaller problem then return the results of those in order to solve the larger one.
Think of how to do this with a loop, and use that to guide what parameters you’ll need for your recursive method.
Example Dialog:
Enter 2 words. I will determine if the letters of one is contained in the other
elf
self
They are contained!
Example Dialog 2:
Enter 2 words. I will determine if the letters of one is contained in the other
jerky
turkey
They are not contained
Example Dialog 3:
Enter 2 words. I will determine if the letters of one is contained in the other
asdf
fasted
They are contained!
Screenshot of the code:


Sample Output:



Code to copy:
import java.util.*;
class StringContainer {
//Define isContained() method returns boolean whether the string contains or not
static boolean isContained(String str1, String str2, int m, int n)
{
//If first string is null then returns true
if(n==0 && m==0)
return true;
if(n==0)
return false;
//Check for each letter one by one and recursively call the isContained() method
if (str1.charAt(m-1) == str2.charAt(n-1))
{
return isContained(str1, str2, m-1, str2.length());
}
else
return isContained(str1, str2, m, n-1);
}
//Define the main method
public static void main(String[] args) {
//create the object of scanner class
Scanner scan=new Scanner(System.in);
//Input two words
System.out.println("Enter 2 words. I will determine if the letters of one is contained in the other");
String s1=scan.next();
String s2=scan.next();
//If second string contains 1st one then print the message
if(isContained(s1, s2, s1.length(), s2.length()))
{
System.out.println("They Are Contained");
}
//If it does not contain the string print accprdingly
else
{
System.out.println("They Are Not Contained");
}
}
}