Write and run Java program. Let L be the language L = {S: S is of the form A ^(2
ID: 3602135 • Letter: W
Question
Write and run Java program.
Let L be the language L = {S: S is of the form A ^(2n) B^(n), for some n >0}
Thus a string is in L if it is empty string or it starts with A followed by a sequence of A’s then followed with half as many B’s example the string AAAABB is in the language.
Write a recursive method that test the input string parameter to see if it belongs to this language and return true or false Now, They must write a driver program to test this method.
The driver program will prompt the user for an input string and test that string. They must prompt the user asking if they want to run the program again. if the user answer no, then they must terminate the program. if it is yes, then run again
Explanation / Answer
import java.util.Scanner;
class Main{
static boolean lan(String s)
{
// base case
if(s.length()==0)
{
return true;
}
else if(s.length()>0 && s.length()<3)
return false;
// main condition which is checking 2 As for 1 B at end
if(s.charAt(0)=='A' && s.charAt(1)=='A' && s.charAt(s.length()-1) == 'B')
{
return lan(s.substring(2,s.length()-1));
}
return false;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice, st;
// taking user input
System.out.print("Enter sequence: ");
st = sc.next();
while(true)
{
// calling function and printing output
System.out.println(lan(st));
// taking user input of choice and string
System.out.print("Wanna continue? Enter yes or no: ");
choice = sc.next();
if(choice.equals("yes"))
{
System.out.print("Enter sequence: ");
st = sc.next();
}
else
{
break;
}
}
}
}
/*
SAMPLE OUTPUT
Enter sequence: AAAABB
true
Wanna continue? Enter yes or no: yes
Enter sequence: AAAAABB
false
Wanna continue? Enter yes or no: yes
Enter sequence: AAB
true
Wanna continue? Enter yes or no: yes
Enter sequence: AAABB
false
Wanna continue? Enter yes or no: no
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.