2014-09-22 385 views
1

如何从键盘输入字符串并重新排列它?例如,在我的情况下,我要求用户以“姓氏,名字”格式导入某人的姓名。然后我必须将其改为“名姓”。如何将Java中的字符串从全名分隔为姓氏和名字?

这是我到目前为止有:

private void setName() { 
    Scanner in = new Scanner(System.in); 
    System.out.println("Please enter the last name followed by the first name of" + 
      "a student: "); 
    name = in.nextLine(); 
} 
+0

查看'String'上的'split()'方法。 – 2014-09-22 23:07:19

+0

预期的输入是什么?例如,我是否为John Doe输入了Doe John或Doe,John?这些将有两种不同的解决方案。 – Compass 2014-09-22 23:07:57

+1

如果字符串互相碰撞,如果不是不可能分开某人的名字和姓氏,那将是非常困难的。 – 2014-09-22 23:08:38

回答

1

一个简单的解决方案是分别询问每个名称,使用两次调用Scanner的nextLine()函数。

import java.util.Scanner; 

public class FirstNameLastName { 
    public static void main(String[] args) { 
     Scanner scan = new Scanner(System.in); 
     System.out.println("Please enter the student's last name: "); 
     String lastName = scan.nextLine(); 

     System.out.println("Please enter the student's first name: "); 
     String firstName = scan.nextLine(); 

     System.out.println("Hello, " + firstName + " " + lastName); 
    } 
} 
1

好了,你可以用它返回一个字符串[]的String.split(”“)。 之后,你所要做的就是以相反的顺序打印字符串。 PS:这不是关于java的,这是关于编程的。

问候。

1

考虑如下

import java.util.Scanner; 

public class Main { 
    public static void main(String[] args) { 
     Scanner in = new Scanner(System.in); 
     System.out.println("Please enter the last name of a student: "); 
     String lastName = in.nextLine(); 

     System.out.println("Please enter the first name of a student: "); 
     String firstName = in.nextLine(); 

     System.out.println(firstName + " " + lastName); 
    } 
} 
1

使用name.split(delimiter)创建两个输入。这将返回一个String数组,并且每个元素都是由分隔符分隔的String组件的一部分,您必须在使用该方法时将其指定为参数。例如,从official Java documentation

The string "boo:and:foo", for example, yields the following results with these expressions: 

Regex Result 
: { "boo", "and", "foo" } 
o { "b", "", ":and:f" } 

方法:
Scanner.nextLine()返回一个字符串。因此,这使变量name一个字符串实例。现在您需要找出String支持哪些方法,以便您可以使用.在实例上调用它。这是通过官方Java documentation for String的时间,并找出可以使用的方法。一旦你找到你想要的方法,你可以谷歌为例:)。