Need assistance with writing this program in Java, please. Write an executable p
ID: 3794880 • Letter: N
Question
Need assistance with writing this program in Java, please.
Write an executable program that has just a main method.
In main:
create an instance of StringBuilder that initially holds an empty string.
append your first name to the string.
append your surname to the string.
display your name.
insert your middle initial where it should be and spaces as needed. If you don't have a middle name, fake it.
display your name with middle initial.
delete your initial and the space(s).
display your name in reverse order.
SAMPLE OUTPUT
John Public
John Q Public
cilbuP nhoJ
Explanation / Answer
// Provided the main function for the program
public static void main(String args[]){
StringBuilder sb=new StringBuilder("");
Scanner in = new Scanner(System.in);
System.out.println("Enter first name");
String firstName = in.nextLine();
System.out.println("Enter Sur name");
String surName = in.nextLine();
sb.append(firstName).append(" ").append(surName);
System.out.println(sb);
String middleName;
System.out.println("Enter the middle Name");
middleName = in.nextLine();
if(middleName.isEmpty()){
// let's fake the middle name
middleName = "Q";
}
// Now we have to find index of first " " in sb.
int index = sb.indexOf(" ");
// Now insert middle name there
sb.insert(index, " " + middleName);
System.out.println(sb);
System.out.println(sb.reverse());
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.