我需要执行以下操作:
许多文档使用特定的格式来表示一个人的名字。编写一个程序,输入为:firstName middleName lastName,输出为:lastName,firstName middleInitial。
这是通过一本教科书进行的,因此还没有教我如何分割字符串。我可以在网上找到所有内容,但这不是教科书所要的。到目前为止,我已经学会了如何比较字符串,获取字符串长度,分支,switch语句,字符串操作。
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String firstName;
String middleName;
String lastName;
String name;
name = scnr.nextLine();
int firstSpace = name.indexOf(" ");
firstName = name.substring(0, firstSpace);
int secondSpace = name.indexOf(" ", firstSpace + 1);
if (secondSpace < 0) {
lastName = name.substring(firstSpace);
System.out.println(lastName + ", " + firstName);
}
else {
middleName = name.substring(firstSpace, secondSpace);
lastName = name.substring(secondSpace);
System.out.println(lastName + ", " + firstName + " " + middleName.charAt(0) + ".");
}
}
}
这是我到目前为止所拥有的。
答案 0 :(得分:0)
如果您不能使用split()
,则可以用scnr.next()
读取前两个条目,然后第三个输入将是该行的其余部分,然后您可以使用其中的一个子字符串作为空格。
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String name1;
String name2;
String name3;
name1 = scnr.next();
name2 = scnr.next();
name3 = scnr.nextLine();
if (name3.equals("")){
System.out.println(name2 + ", " + name1);
}
else{
name3 = name3.substring(1);
System.out.println(name3 + ", " + name1 + " " + name2.charAt(0) + ".");
}
}
}
答案 1 :(得分:0)
这是正确的代码:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String firstName;
String middleName;
String lastName;
String name;
name = scnr.nextLine();
int firstSpace = name.indexOf(" ");
firstName = name.substring(0, firstSpace);
int secondSpace = name.indexOf(" ", firstSpace + 1);
if (secondSpace < 0) {
lastName = name.substring(firstSpace + 1);
System.out.println(lastName + ", " + firstName);
}
else {
middleName = name.substring(firstSpace, secondSpace);
lastName = name.substring(secondSpace + 1);
System.out.println(lastName + ", " + firstName + " " + middleName.charAt(1) + ".");
}
}
}