2014-09-19 120 views
1

所以我的目标是重新排列输入到程序中的字符串,以便输出相同的信息,但顺序不同。输入顺序是firstNamemiddleNamelastNameemailAddress和期望的输出是lastNamefirstNamefirst letter of middleName.重新排列字符串

例如输入

JohnJackBrown[email protected]

将输出

BrownJohnJ.

这里是我到目前为止

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的第一个字母后跟一个.

回答

0

这符合您的要求输出。

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


    } 

} 
0

选中此项。

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: "); 
     System.out.println(rearrangeName(keyboard.nextLine())); 
    } 

    public static String rearrangeName(String inputName) { 
     String[] fml = inputName.split(" |,"); // Separate by space and , 
     return fml[2] + ", " + fml[0] + " " + fml[1].charAt(0) + "."; 
    } 
} 
+0

上'也许拆分 “\\ S * | \\ S +”',它(对于@moo的利益)指在任分流/或('|')逗号后跟零个或更多('\\ s *')或没有逗号,但有一个或多个空格('\\ s +')。这为用户输入提供了更多的灵活性。 – 2014-09-19 02:42:31

0

您还需要为空格分隔字符串。并且不要忘记替代的“|”字符。尝试以下操作。

String[] fml = entireLine.split(" |, "); 
+0

唯一的问题是每个空间都代表一个新元素。如:John Joe,Doe,[email protected]会= 6个元素而不是所需的4个。 – MarGar 2014-09-19 02:39:44