Write a menu driven program in Java to display the pattern of a String entered by the user. If the user enters "first" then it displays the first character of each word and if the user enters “last" the user displays "last" character of each word. Eg: Sample input: "Java is fun to learn” Sample output: choice is First choice is last
j. a
l. s
f. n
t. o
l. n
Answers
Answer:
import java.util.*;
public class FirstLast{
public static void main(String[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the string");
String data = in.nextLine();
System.out.println("Enter first or last");
String choice = in.next();
String[] words = data.split(" ");
//splitting the words by space
switch(choice.toLowerCase()){
case "first":
for(int i=0; i<words.length;i++)
System.out.println(words[i].charAt(0));
break;
case "last":
for(int i=0; i<words.length;i++)
System.out.println(words[i].charAt(words[i].length-1));
break;
default:
System.out.println("Wrong choice");
}
}
}
// This program worked for me hope it works for you as well
// Ignore the new lines for the statements and write it continuously
Answer:
import java.util.*;
public class FirstLast
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
String S="";
char c='\u0000', a='\u0000';
int l=0;
System.out.println("Enter String");
S=in.nextLine();
System.out.println("Enter Choice");
System.out.println("F-First Letter; L-Last Letter");
c=in.next().charAt(0);
switch(c)
{
case 'F':
S=' '+S;
l=S.length();
for(int i=0; i<l; i++)
{
a=S.charAt(i);
if(a==' ')
System.out.println(S.charAt(i+1));
}
break;
case 'L':
S=S+' ';
l=S.length();
for(int i=0; i<l; i++)
{
a=S.charAt(i);
if(a==' ')
System.out.println(S.charAt(i-1));
}
break;
default:
System.out.println("Wrong Choice");
}
}
}