当用户输入多个空格时,我的程序无法正确打印用户的名称。例如,如果用户输入他们的名字后跟2个空格然后输入他们的姓氏,我的程序会假设这些额外的空格是中间名,并将中间名作为空格打印,将姓氏打印为输入的第二个字符串,即使只输入了两个字符串。如何改善此问题,以便用户可以输入的额外空间不算作中间名或姓?
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the name parser.\n");
System.out.print("Enter a name: ");
String name = sc.nextLine();
name = name.trim();
int startSpace = name.indexOf(" ");
int endSpace = name.indexOflast(" ");
String firstName = "";
String middleName = "";
String lastName = "";
if(startSpace >= 0)
{
firstName = name.substring(0, startSpace);
if(endSpace > startSpace)
{
middleName = name.substring(startSpace + 1, endSpace);
}
lastName = name.substring(endSpace + 1, name.length());
}
System.out.println("First Name: " + firstName);
System.out.println("Middle Name: " + middleName);
System.out.println("Last Name: " + lastName);
}
输出:joe mark
First name: joe
Middle name: // This shouldn't print but because the user enter extra spaces after first name the spaces becomes the middle name.
Last name: mark
答案 0 :(得分:3)
试试这个
// replaceAll needs regex so "\\s+" (for whitespaces)
// s+ look for one or more whitespaces
// replaceAll will replace those whitespaces with single whitespace.
// trim will remove leading and trailing whitespaces
name = name.trim().replaceAll("\\s+", " ");