In: Computer Science
Write a JAVA program that contains the following 4 void methods whic will print all subtrings of s in specific orders: printSub1(String s), printSub2(String s), printSub3(String s), and printSub4(String s)
For example, if S = "abcd":
printSub1 will print "a", "ab", "abc", "abcd", "b", "bc", "bcd", "c", "cd", "d"
printSub2 will print "a", "ab", "b", "abc", "bc", "c", "abcd", "bcd", "cd", "d"
printSub3 will print "d", "c", "b", "a", "cd", "bc", "ab", "bcd", "abc", "abcd"
printSub4 will print "abcd", "bcd", "abc", "cd", "bc", "ab", "d", "c", "b", "a"
(Note: the actual output will not have quotation marks around the substrings.)
Create a menu in your main method using a switch statement inside of a do…while loop so the user can repeatedly choose which method to execute from the menu. The user should be asked to input the string in your main method before the menu is presented to them.
Additional Assignment Requirements
1. You must use NESTED FOR LOOPS to do the work in each method in this lab.
2. YOU MAY NOT USE any concepts not yet taught in this course like ARRAYS.
3. The only built-in String methods you can use are length() and substring().
4. You must work with everything as Strings.
5. If appropriate for this algorithm, you should validate any input from the user to make sure the data input is an appropriate value to work in your program’s logic. You don’t have to worry about validating that it is the correct data type. For now, assume the user is only giving you the correct data type and just worry about validating the value given is usable in your program.
import java.util.*;
public class Main
{
public static void printSub1(String s){
int n=s.length();
for(int i=0;i<n;i++){
for(int j=i+1;j<=n;j++){
System.out.print(s.substring(i,j)+" ");
}
}
System.out.println();
}
public static void printSub2(String s){
int n=s.length();
for(int i=1;i<=n;i++){
for(int j=0;j<i;j++){
System.out.print(s.substring(j,i)+" ");
}
}
System.out.println();
}
public static void printSub3(String s){
int n=s.length();
for(int i=1;i<=n;i++){
for(int j=n-i;j>=0;j--){
System.out.print(s.substring(j,j+i)+" ");
}
}
System.out.println();
}
public static void printSub4(String s){
int n=s.length();
for(int i=n;i>0;i--){
for(int j=n-i;j>=0;j--){
System.out.print(s.substring(j,j+i)+" ");
}
}
System.out.println();
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String s=scanner.next();
boolean flag=true;
while(flag){
System.out.println("Enter option to be executed in range 1-4");
int option=scanner.nextInt();
switch(option){
case 1: printSub1(s);break;
case 2: printSub2(s);break;
case 3: printSub3(s);break;
case 4: printSub4(s);break;
default: flag=false;
}
}
}
}
if we get any option other than 1-4, then we will exit the menu.