当用户输入多个空格时,我的程序无法正确打印出用户名,例如,如果用户打印名字后跟 2 个空格,然后是姓氏中间名,然后打印为空格,最后一个 nmae 打印? ? 我该如何改进这个问题,以便用户输入的额外空间不计为中间名或姓氏?
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);
}
}
输出:乔马克
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