要求:
- 编写Java程序,输入样式为:Zhong wen ming的人名,以 Ming,Zhong.W 的形式打印出来。其中.W是中间单词的首字母;
- 例如输入”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;}
打印结果:
第二种实现方法:
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);}