2013-04-15 50 views
-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 
+6

为什么今天第二次问同样的问题? – piokuc

+0

其不一样 – user2264244

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

1. Java Regex

2. replaceAll API

+4

你应该解释这是什么。 –

+0

@MattBall就是这么做的。不管怎么说,还是要谢谢你。 – Smit