/** * stringReformat takes a person\'s name in the format and * reformats it to
ID: 3706837 • Letter: #
Question
/** * stringReformat takes a person's name in the format and * reformats it to the form * * Preconditions: * the string is not empty * there is exactly one ',' (comma) and it comes at the end of the Last name * there is 1 space after the comma * there is exactly one space between the First name and the Initial * The Initial is a single character followed by a '.' * * Here are some examples (using "==" informally): * *
*/ public static String stringReformat( String name) { String theAnswer = "this is not the answer"; // example code starts here: delete or comment out when you have completed the function String subExample = name.substring(1,5); // some example code char theChar = name.charAt(4); System.out.println(" stringReformat demo1. the substring(1,5) is: " + subExample); if ( theChar == ',' ) System.out.println(" stringReformat demo2. the character in position 4 is a comma"); else System.out.println(" stringReformat demo2. the character in position 4 is NOT a comma, it is: "+ theChar); // end of example code return theAnswer; // TODO 3: fix this.
Explanation / Answer
public class StringReformatTest {
public static void main(String[] args) {
stringReformat("Keaton, Alex P.");
stringReformat("Boyd, Luke A.");
}
public static void stringReformat( String name) {
String s = "";
int i;
for(i=0;i<name.length();i++) {
if(name.charAt(i)==',') {
break;
}
}
s = name.substring(i+2, name.length()-1)+" "+name.substring(0,i);
System.out.println(s);
}
}
Output:
Alex P Keaton
Luke A Boyd
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.