Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Oct 2011
    Posts
    27
    Thanks
    2
    Thanked 0 Times in 0 Posts

    How to put names in alphabetical order

    This is what I got but im getting an error in the if statements, so can someone help me fix this?


    import java.util.Scanner;

    public class Alpha
    {
    public static void main(String[] args)
    {
    String = name1;
    String = name2;
    String = name3;
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter name one");
    name1 = keyboard.nextLine();
    System.out.println("Enter name two");
    name2 = keyboard.nextLine();
    System.out.println("Enter name three");
    name3 = keyboard.nextLine();

    if(name1.compareTo(name2) < 0) && (name1.compareTo(name3) < 0) && (name2.compareTo(name3) < 0)
    {
    System.out.println(name1 + name2 + name3);
    }
    else if(name2.compareTo(name1) < 0) && (name2.compareTo(name3) < 0) && (name1.compareTo(name3) < 0)
    {
    System.out.println(name2 + name1 + name3);
    }
    else if(name3.compareTo(name1) < 0) && (name3.compareTo(name2) < 0) && (name1.compareTo(name2) < 0)
    {
    system.out.println(name3 + name1 + name2);
    }

    }
    }

  • #2
    Senior Coder alykins's Avatar
    Join Date
    Apr 2011
    Posts
    1,662
    Thanks
    41
    Thanked 189 Times in 188 Posts
    you can make this a lot easier on yourself if you add the strings to either an array or a list and then use the sort method
    string array
    collection

    I code C hash-tag .Net
    Reference: W3C W3CWiki .Net Lib
    Validate: html CSS
    Debug: Chrome FireFox IE

  • #3
    New Coder
    Join Date
    Oct 2011
    Posts
    27
    Thanks
    2
    Thanked 0 Times in 0 Posts
    but why am i getting an error at the "Logical && " ....are you allowed to used the logical && with equals method in java?

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    Because the if branch has been terminated: if(name1.compareTo(name2) < 0). Following && and anything after is a stynax error.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •