-3

当用户输入多个空格时,我的程序无法正确打印出用户名。例如,如果用户输入他们的名字后跟 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);
}

输出:乔马克

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 
4

1 回答 1

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+", " ");

1.Java正则表达式

2.替换所有API

于 2013-04-15T21:46:03.317 回答