【发布时间】:2015-10-09 17:55:19
【问题描述】:
我正在为这段代码苦苦挣扎。这个返回的是例如:“JS John Smith”但是当我尝试把两个名字加上姓氏时,我得到的只是一团糟。我希望在我输入时得到例如:“John William Smith”这样的东西:“JW Smith”,有人知道怎么做吗?
import java.io.*;
import java.io.BufferedReader;
public class ex54 {
public static void main(String[] args) {
System.out.print("Enter your name: ");
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
String fullName = null;
try{
fullName = br.readLine();
} catch (IOException ioe) {
System.out.println("Error");
System.exit(1);
}
int spacePos = fullName.indexOf(" ");
// String firstName = fullName.substring(0, spacePos);
// String secondName = fullName.substring(1, spacePos);
String firstInitial = fullName.substring(0, 1);
String secondInitial = fullName.substring(spacePos+1, spacePos+2);
String userName = (firstInitial + secondInitial + " ").concat(fullName);
System.out.println("Hello, your user name is: " + userName);
}
}
}
【问题讨论】:
-
split的好人选