How can I shorten this Java code? -


/* program sorts out name in orders first alphabetical orders .*/  package nameorder;  public class nameorder {      public static void sayname(string a, string s, string d){         system.out.println("name alphabetical order: \n1."+a+"\n"+"2."+s+"\n3."+d+"\n");      }      public static void stringorder(string ,string s ,string d){         int i= a.compareto(s) ;         int j= a.compareto(d) ;         int k= d.compareto(s) ;         int l= d.compareto(a) ;         string first="";         string second="";         string third="";             if(i<0&&j<0){                 first=a;                     if(k>0&&l>0){                         third = d;                         second = s;                     }else{                         second = d;                         third = s;                     }             }else if(i>0&&j>0){                 third=a;                     if(k<0&&l<0){                         first = d;                         second = s;                     }else{                         second = s;                         first = d;                     }             }else{                 second=a;                     if(k<0&&l<0){                         first = d;                         third = s;                     }else{                         first = s;                         third = d;                     }             }         sayname(first,second,third);         }      public static void main(string[] args) {         string ="c";         string s ="a";         string d ="h";         stringorder(a.touppercase(),s.touppercase(),d.touppercase());      }  } 

i'm wondering if i'm doing right or there better shorter version this?

from perspective of "sorting 3 strings", need 3 comparisons , lose temp variables.

public static void stringorder(string a, string s, string d) {     string tmp;      if (a.compareto(s) > 0) {         tmp = a;         = s;         s = tmp;     }      if (a.compareto(d) > 0) {         tmp = a;         = d;         d = tmp;     }      if (s.compareto(d) > 0) {         tmp = s;         s = d;         d = tmp;     }      sayname(a, s, d); } 

but maintainability perspective, use facilities built java sort multiple strings @ time:

public static void stringorder(string a, string s, string d) {     string [] arr = {a, s, d};     java.util.arraylist<string> list = new arraylist<string>(arrays.aslist(arr));     java.util.collections.sort(list);     sayname(list.get(0), list.get(1), list.get(2)); } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -