|
20鱼币
- package test1;
- public class Name {
- protected String firstName,lastName;
-
- public Name(String firstName, String lastName) {
- this.firstName = firstName;
- this.lastName = lastName;
- }
-
- public String getFirst() {return firstName;}
- public String getLast() {return lastName;}
-
- public static void main(String[] args) {
- String nameS1 = "Jiakai He";
- String nameS2 = "Kong, Jason";
- Name name1 = NameFactory.getName(nameS1);
- Name name2 = NameFactory.getName(nameS2);
- System.out.println(nameS1 + ", first name:" + name1.getFirst() +
- ", last name:"+name1.getLast());
- System.out.println(nameS2 + ", first name:" + name2.getFirst() +
- ", last name:"+name2.getLast());
- }
- }
- class FirstFirst extends Name {
- public FirstFirst(String firstName, String lastName) {
- super(firstName, lastName);
- }
-
- }
-
- class LastFirst extends Name {
- public LastFirst(String firstName, String lastName) {
- super(firstName, lastName);
- }
- }
- class NameFactory {
- public static Name getName(String s) {
- String[] parts = s.split(" ");
- if (parts.length == 2) {
- // 判断 "first last" 格式
- return new FirstFirst(parts[0], parts[1]);
- } else if (s.contains(",")) {
- // 判断 "last, first" 格式
- String[] commaParts = s.split(", ");
- return new LastFirst(commaParts[1], commaParts[0]);
- } else {
- throw new IllegalArgumentException("不合法格式");
- }
- }
- }
复制代码 这里的NameFactory,我想按照是否有空格与是否有逗号分类,但是始终没办法进入else if 语句,而且最终输出的结果也有问题,请问大佬们这是为什么呢
问题在于判断逗号的代码中使用了 s.contains(",") ,这个条件不够严谨,因为名字中可能会包含逗号,例如 "Smith, John Jr."。应该使用 s.indexOf(",") != -1 来判断是否有逗号。另外,判断空格的代码可以使用 s.indexOf(" ") != -1 来代替 s.split(" ").length == 2 ,这样可以避免不必要的字符串分割操作。修改后的代码如下:
- class NameFactory {
- public static Name getName(String s) {
- if (s.indexOf(",") != -1) { // 判断 "last, first" 格式
- String[] commaParts = s.split(", ");
- return new LastFirst(commaParts[1], commaParts[0]);
- } else if (s.indexOf(" ") != -1) { // 判断 "first last" 格式
- String[] parts = s.split(" ");
- return new FirstFirst(parts[0], parts[1]);
- } else {
- throw new IllegalArgumentException("不合法格式");
- }
- }
- }
复制代码
这样就可以正确地判断名字格式并创建相应的对象了。
|
最佳答案
查看完整内容
问题在于判断逗号的代码中使用了 s.contains(",") ,这个条件不够严谨,因为名字中可能会包含逗号,例如 "Smith, John Jr."。应该使用 s.indexOf(",") != -1 来判断是否有逗号。另外,判断空格的代码可以使用 s.indexOf(" ") != -1 来代替 s.split(" ").length == 2 ,这样可以避免不必要的字符串分割操作。修改后的代码如下:
这样就可以正确地判断名字格式并创建相应的对象了。
|