2014-09-19 5 views
1

내 목표는 프로그램에 입력 된 문자열을 다시 정렬하여 같은 정보를 다른 순서로 출력하도록하는 것입니다. , firstNamefirst letter of middleName.문자열 재정렬

입력

JohnJack, Brown 입력 순서 firstNamemiddleName, lastName, emailAddress이고 의도 출력 lastName이다 [email protected]

것 출력

Brown, John여기 .

내가 가진 무엇 지금까지

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 그래서 나는 .

답변

0

다음에 middleName의 첫 글자를 substring() 수 분리하는 방법을 알아낼 수 없습니다 이것은 필요한 출력을 충족시킵니다.

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의 이익을 위해)이 하나의 분할 수단/또는 ('|')하는 0 개 이상의 다음 쉼표 공백 ('\\ s *') 또는 쉼표가 없지만 하나 이상의 공백 ('\\ s +'). 이렇게하면 사용자 입력에 대한 유연성이 조금 더 높아집니다. –

0

공백을 구분하려면 문자열을 구분해야합니다. 그리고 대체 "|" 캐릭터. 다음을 시도하십시오.

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

유일한 문제는 모든 공간이 새로운 요소를 나타냅니다. 예 : John Joe, Doe, [email protected]은 원하는 4 대신 6 개의 요소를 갖습니다. – MarGar