In: Computer Science
You are to write a class StringPlay that has only a main method. This class contains all interaction with the user.
The main method
Notes
Use Scanner’s next method for the “e” command; we will limit our user input to have no spaces or other whitespace. Similarly, padding characters will not be whitespace. You may assume valid user input.
Sample Output:
The screenshots are attached below for reference.
Please follow them for proper output.
Program code to copy:
import java.util.*;
public class StringPlay{
public static void main (String[] args) {
Scanner inp=new Scanner(System.in);
String current="";
System.out.println("Enter the current string:");
current=inp.next();//read current string
char ch='a';
int n=0;
while(ch!='f'){
System.out.println("The current string is:"+current);//print
current string
System.out.println("a-Enter a new value for current:");
System.out.println("b-padLeft");//print menu options
System.out.println("c-padRight");
System.out.println("d-zapLeft");
System.out.println("e-zapRight");
System.out.println("f-exit");
System.out.println("Enter choice:");
ch=inp.next().charAt(0);//read choice from user
if(ch=='a'){
System.out.println("Enter the value for current string:");
current=inp.next();
}
else if(ch=='b'){
System.out.println("Enter number of characters to add:");
n=inp.nextInt();
System.out.println("Enter character:");//read input from user
ch=inp.next().charAt(0);
String res="";
for(int i=0;i<n;i++){
res=res+ch;//create a new string and add characters at front
}
res+=current;
current=res;///update current with res string
}
else if(ch=='c'){
System.out.println("Enter number of characters to add:");
n=inp.nextInt();
System.out.println("Enter character:");
ch=inp.next().charAt(0);//read input from user
for(int i=0;i<n;i++){
current=current+ch;//add characters
}
}
else if(ch=='d'){
System.out.println("Enter number of characters to remove:");
n=inp.nextInt();//read input from user
n=n-1;
String res="";
for(int i=n;i<current.length();i++){
res=res+current.charAt(i);//add charaters to res String from
current string after n positions
}
current=res;
}
else if(ch=='e'){
System.out.println("Enter number of characters to remove:");
n=inp.nextInt();
String res="";
for(int i=0;i<current.length()-n;i++){
res=res+current.charAt(i);//add characters to res from current
string till n characters from last
}
current=res;
}
else{
break;
}
}
}
}