如何获取从键盘输入的字符串并重新排列它?例如,在我的例子中,我要求用户以“姓氏,名字”格式导入一个人的名字。然后我必须将其更改为“名字姓氏”。
这是我到目前为止所拥有的:
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();
}
最佳答案
一个简单的解决方案是使用对 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);
}
}
关于java - 如何将Java中的字符串从全名分隔为姓氏、名字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25984389/