-3

ユーザーが複数のスペースを入力すると、私のプログラムはユーザーの名前を正しく出力しません。たとえば、ユーザーが名の後に 2 つのスペースを入力し、次に姓を入力すると、私のプログラムはそれらの余分なスペースがミドル ネームであると想定し、ミドル ネームをスペースとして出力し、姓を 2 番目に入力された文字列として出力します。 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.replaceAll API

于 2013-04-15T21:46:03.317 に答える