将中文名格式化输出为英文名

要求:

  1. 编写Java程序,输入样式为:Zhong wen ming的人名,以 Ming,Zhong.W 的形式打印出来。其中.W是中间单词的首字母;
  2. 例如输入”Willian Jefferson Clinton“,输出形式为:Clinton,Willian.J
  public static void main(String[] args) {
        try {
            englishName("Xiao Mo Nian");
            englishName("Willian Jefferson Clinton");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    public static void englishName(String name){
        if(name==null){
            throw new RuntimeException("输入姓名不能为空");
        }
        String[] spilt = name.split(" ");
        if(spilt.length!=3){
            throw new RuntimeException("您输入的姓名格式不正确");
        }
        String twoSpilt = new String(spilt[1]);
        char lastNameOne = twoSpilt.charAt(0);
        lastNameOne = isprimeChar(lastNameOne);
        for (int i = 0; i < spilt.length; i++) {
            if(i == spilt.length-1){
                System.out.println(spilt[i]+","+spilt[0]+"."+lastNameOne);
            }
        }
    }
    public static char isprimeChar(char twoChar){
        char reverChar = twoChar;
        if(!(twoChar>='A'&&twoChar<='Z')){
            reverChar = (char)(twoChar-32);
        }
        return reverChar;
    }

 打印结果:

将中文名格式化输出为英文名_第1张图片

第二种实现方法:
public static void englishName(String name){
        String[] spilt = name.split(" ");
        if(spilt.length!=3){
            throw  new RuntimeException("输入的格式不正确");
        }
        if(name==null){
            throw new RuntimeException("输入不能为空");
        }
//        String formatStr ="%s,%s.%c";
//        String info =                     String.format(spilt[2]+","+spilt[0]+"."+spilt[1].toUpperCase().charAt(0));
        String info = String.format("%s,%s.%c",spilt[2],spilt[0],spilt[1].toUpperCase().charAt(0));
        System.out.println(info);
    }

你可能感兴趣的:(韩顺平java习题,java,算法,开发语言)