你如何从键盘输入一个字符串并重新排列?例如,在我的情况下,我要求用户在"姓氏,名字"中输入一个人的姓名。格式。然后我必须将其改为"首先命名姓氏"。
这是我到目前为止所做的:
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 :(得分:1)
好吧,你可以使用返回String []的String.split(“”)。 之后,您只需按逆序运行此数组即可打印字符串。
String[] tokens = name.split(" "); // split line on string separated by " "
for(int i = tokens.length - 1; i >= 0; i--)
System.out.println(tokens[i]);
PS:这不是关于java,而是关于编程。
问候。
答案 1 :(得分: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);
}
}
答案 2 :(得分: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()
返回一个String。这样,变量name
就成了一个String 实例。现在您需要找出String支持哪些方法,以便您可以使用.
在实例上调用它。现在是时候通过官方Java documentation for String,找出可以使用的方法。找到所需的方法后,您可以通过Google获取示例:)。
答案 3 :(得分: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);
}
}
答案 4 :(得分:0)
import java.util.Scanner;
public class SpaceReplace {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String firstName;
String lastName;
firstName = scnr.next();
lastName = scnr.next();
System.out.println(lastName + ", " + firstName);
} }