java - 如何将Java中的字符串从全名分隔为姓氏、名字?

标签 java string

如何获取从键盘输入的字符串并重新排列它?例如,在我的例子中,我要求用户以“姓氏,名字”格式导入一个人的名字。然后我必须将其更改为“名字姓氏”。

这是我到目前为止所拥有的:

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/

相关文章:

java - RMI 远程异常。 RMI 不工作

java - 使用%找零时给出错误的数字

swift - 从另一个 TableView 添加行 - Swift

Java - 长时间到 ISO_8601 字符串格式

java - JAXB wsimport 绑定(bind)文件是否可能(实现接口(interface))。告诉它是

java - 方法引用 Bound Receiver 和 Unbound Receiver 的区别

php - 在数组的每个可能组合中创建几个单词

swift - 将字符串转换为日期会分配错误的值

存储在 LPCSTR 中的 C++ 字符 .. 损坏了吗?

java - 未弃用的 StringBufferInputStream 等价物