sorting - Second console prompt fails in Java -


this class assignment have user input 3 names, sort them alphabetically in descending or ascending order based again on user input. i've got input of names down , managed find way sort them code fails when ask user choose between ascending , descending (ie: following if statements don't execute). i'm sure it's simple explanation haven't been able figure out i'm doing wrong.

here's code:

package javaapplication9;  import java.util.scanner;  public class javaapplication9 {  public static void main(string[] args) {     string = getinput("enter first name: ");     string b = getinput("enter second name: ");     string c = getinput("enter third name: ");     string ascending = getinput("enter [a] ascending , [d]"             + "for descending order.");      // find first name alphabetically     string min = "";     if (a.compareto(b) <= 0 && a.compareto(c) <= 0)     {         min = a;     }     else if (b.compareto(a) <= 0 && b.compareto(c) <= 0)     {         min = b;     }     else if (c.compareto(b) <= 0 && c.compareto(a) <= 0)     {         min = c;     }      // find middle name alphabetically (and descending order)     string middle = "";     if (a.compareto(b)*a.compareto(c) <= 0)     {         middle = a;     }     else if (b.compareto(a)*b.compareto(c) <= 0)     {         middle = b;     }     else if (c.compareto(b)*c.compareto(a) <= 0)     {         middle = c;     }      // find last name alphabetically     string last = "";     if (a.compareto(b) >= 0 && a.compareto(c) >= 0)     {         last = a;     }     else if (b.compareto(a) >= 0 && b.compareto(c) >= 0)     {         last = b;     }     else if (c.compareto(b) >= 0 && c.compareto(a) >= 0)     {         last = c;     }      // having difficulty. part of program      // never executes when run file , can't seem figure     // out why.     if (ascending == "a")     {         system.out.println(min + " " + middle + " " + last);     }     if (ascending == "d")     {         system.out.println(last + " " + middle + " " + min);     }  } // end main function  private static string getinput(string prompt) {     system.out.print(prompt);     scanner sc = new scanner(system.in);     return sc.nextline(); } } 

to compare strings in java need use equals(string compare) method of string class.

because tell user enter uppercase letters, use equalsignorecase method instead:

if(ascending.equalsignorecase("a")) {     system.out.println(min + " " + mid + " " + last); } 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -