moo moo - 24 days ago 8
Java Question

Rearranging a string

So my goal is to rearrange a string that is inputted into the program so that it outputs the same info but in a different order. The input order is

firstName
middleName
,
lastName
,
emailAddress
and the intended output is
lastName
,
firstName
first letter of middleName
.


For example the input

John
Jack
,
Brown
,
JJB@yahoo.com


would output

Brown
,
John
J
.


Here's what I have so far

import java.util.Scanner;

public class NameRearranged {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name like D2L shows them: ");
String entireLine = keyboard.nextLine();
String[] fml = entireLine.split(",");
String newName = fml[0].substring(7);
String newLine = fml[1] + "," + newName + ".";
System.out.println(newLine);
}

public String substring(int endIndex) {
return null;
}
}


I can't figure out how to separate the
firstName
and
middleName
so I can
substring()
the first letter of the
middleName
followed by a
.

Answer

This meets your required output.

import java.util.Scanner;

public class NameRearranged {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter a name like D2L shows them: ");
        String entireLine = keyboard.nextLine();

        String[] fml = entireLine.split(","); //seperate the string by commas

        String[] newName = fml[0].split(" "); //seperates the first element into 
                                              //a new array by spaces to hold first and middle name

        //this will display the last name (fml[1]) then the first element in 
        //newName array and finally the first char of the second element in
        //newName array to get your desired results.
        String newLine = fml[1] + ", " + newName[0] + " "+newName[1].charAt(0)+".";

        System.out.println(newLine);


    }

}
Comments