所以我的目标是重新排列输入到程序中的字符串,以便它以不同的顺序输出相同的信息。输入顺序为firstName
middleName
,lastName
,emailAddress
,预期输出为lastName
,firstName
first letter of middleName
{{1 }}
例如输入
.
John
,Jack
,Brown
会输出
JJB@yahoo.com
,Brown
John
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;
}
}
和firstName
分开,以便我可以middleName
substring()
的第一个字母后跟middleName
答案 0 :(得分: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);
}
}
答案 1 :(得分: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) + ".";
}
}
答案 2 :(得分:0)
您还需要为空格分隔字符串。并且不要忘记候补" |"字符。请尝试以下方法。
String[] fml = entireLine.split(" |, ");