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

最佳答案

这行:

int endSpace = name.indexOf(" ");


应该:

int endSpace = name.lastIndexOf(" ");

关于java - 解析全名?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16021218/

10-11 09:26