Advertisement
Guest User

Untitled

a guest
Jul 24th, 2014
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.27 KB | None | 0 0
  1. package nameformatter;
  2.  
  3. public class NameFormatter {
  4.     private String unformedName;
  5.     private String formedName;
  6.     private String nameA;
  7.     private String nameB;
  8.     private String nameC;
  9.    
  10.     public NameFormatter(String name) {
  11.         this.unformedName = "Unknown";
  12.         this.formedName = "Unknown";
  13.         this.nameA = "";
  14.         this.nameB = "";
  15.         this.nameC = "";
  16.         this.setName(name);
  17.         this.formatName();
  18.     }
  19.    
  20.     private void setName(String name) {
  21.         this.unformedName = name;
  22.     }
  23.    
  24.     public String formatName() {
  25.         // The below block catches middle initial
  26.         if (this.unformedName.length() == 1) {
  27.             this.formedName = this.unformedName;
  28.             return this.formedName;
  29.         }
  30.         // This check ensures we capture instances of multiple first name
  31.         try {
  32.             String[] names = this.unformedName.split("\\s+");
  33.             if (names.length == 2) {
  34.                 this.nameA = names[0].substring(0, 1) +
  35.                        this.nameA.substring(1).toLowerCase();
  36.                 this.nameB = names[1].substring(0, 1) +
  37.                        this.nameB.substring(1).toLowerCase();
  38.                 this.formedName = this.nameA + " " + this.nameB;
  39.                 return this.formedName;
  40.             }
  41.             else if (names.length == 3) {
  42.                 this.nameA = names[0].substring(0, 1) +
  43.                        this.nameA.substring(1).toLowerCase();
  44.                 this.nameB = names[1].substring(0, 1) +
  45.                        this.nameB.substring(1).toLowerCase();
  46.                 this.nameC = names[2].substring(0, 1) +
  47.                        this.nameC.substring(1).toLowerCase();
  48.                 this.formedName = nameA + " " + nameB + " " + nameC;
  49.                 return this.formedName;
  50.             }
  51.             else {
  52.                 this.formedName = this.unformedName.substring(0, 1) +
  53.                      this.unformedName.substring(1).toLowerCase();
  54.                 return this.formedName;
  55.             }
  56.         }
  57.         catch(Exception e) {
  58.             this.formedName = this.unformedName.substring(0, 1) +
  59.                  this.unformedName.substring(1).toLowerCase();
  60.             return this.formedName;
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement