2014-09-19 129 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