因此,我的目标是重新排列输入到程序中的字符串,以使其输出相同的信息,但顺序不同。输入顺序为firstName middleNamelastNameemailAddress,预期的输出为lastNamefirstName first letter of middleName .

例如输入

John JackBrown[email protected]

将输出

BrownJohn J .

这是我到目前为止的

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;
  }
}


我不知道如何分隔firstNamemiddleName,所以我可以substring() middleName的第一个字母,后跟.

最佳答案

这符合您所需的输出。

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);


    }

}

09-13 07:23