Java5: Sort and print out names (user inputs) alphabetically

Dear experts:

Hi again!

I am trying to write a simple code to get  client names from clients, and alphabetically sort and print out them.

The code (as it is) is very poor, and requires a tremendous improvement. I really like to learn how to write a code which is best functioning and most professional (?).

Hope you experts may kindly help me with tghe code.

Thanks a lot!



--------------------- Here is my very poor code --------------------------------------------------------------------------
iimport javax.swing.*;


public class java
{
  static void main (String[] args)
  {
      java duta = new java ();
      duta.sortNames ();
      System.exit (0);
  }
 
   
  public String [] getNames ()
  {
    int max = 7;
   
   
    String [] names = new String [max];
   
    int i;
    for (i = 1; i <= max; i++ )
    {
       names[i] = getInput ("Enter a name.");  // get seven names from users.

     }
   
    return names;    


 }
     
     
   
  public String getInput (String msg)
  {
    String name = JOptionPane.showInputDialog (msg);
    return name;
  }
 
  public void sort_outputNames ( )
  {
    String [] names = getNames ();  // codes to alphabetically sort names
   
   
   display (sorted names) // display sorted names

  }
 
  }
 
 
   
 
 
 
  public void display (String msg)
  {
     JOptionPane.showMessageDialog (null, msg);    
  }
 
 
 
 
}
 
 
   
   
 
 
dutaAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
matthew016Connect With a Mentor Commented:
Some quick comments :

1)
In Java we use to name a class with an upper case letter.
So instead of java, make it Java.

2)
This class need a main method if u want to be able to run it,
I can see in your code :

  static void main (String[] args)
  { [...] }

But it must be

  public static void main (String[] args)
  { [...] }

That's a convention as well for a class to be able to run.

3)
This code throws an exception :

    int max = 7;
   
   
    String [] names = new String [max];
   
    int i;
    for (i = 1; i <= max; i++ )
    {
       names[i] = getInput ("Enter a name.");  // get seven names from users.

     }

U specify an array of size 7 : so u can put a value in case 0, 1, 2, 3 , 4, 5, 6 in the array.

Look at what u are doing in the loop :
U don't put any values in array 0, and u put values in 1,2,3,4,5,6,7,8 but thius will throw u an ArrayIndexOutOfBoundsException since there is no "8".

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
      at java.getNames(java.java:24)
      at java.sortNames(java.java:43)
      at java.main(java.java:9)
0
 
matthew016Commented:
Let me correct one sentence :

"U don't put any values in array 0, and u put values in 1,2,3,4,5,6,7,8 but thius will throw u an ArrayIndexOutOfBoundsException
since there is no "8"."

must be

"U don't put any values in array 0, and u put values in 1,2,3,4,5,6,7 but thius will throw u an ArrayIndexOutOfBoundsException
since there is no "7".
But only from 0 to 6
0
 
matthew016Commented:
Here is your code improved :

import java.util.Arrays;
import javax.swing.JOptionPane;
public class Java
{
  public static void main (String[] args)
  {
      Java duta = new Java ();
      duta.sortNames ();
  }
  public String [] getNames ()
  {
    int max = 7;
    String [] names = new String [max];
    int i;
    for (i = 0; i < max; i++ )
    {
       names[i] = getInput ("Enter a name.");  // get seven names from users.
     }
    return names;    
 }
  public String getInput (String msg)
  {
    String name = JOptionPane.showInputDialog (msg);
    return name;
  }
  public void sortNames ( )
  {
    String [] names = getNames ();  // codes to alphabetically sort names
    Arrays.sort(names);
    display (names); // display sorted names
  }
  public void display (String [] names)
  {
     JOptionPane.showMessageDialog (null, names);
  }
}
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
dutaAuthor Commented:
Dear Matthew:
You are a genuius. That is awesome.

By the way, may I ask a quick question?

How may I print out the names that comes first and last in the sorted names?

Thanks!
0
 
matthew016Commented:
JOptionPane.showMessageDialog (null, names[0]+"\n"+names[names.length-1]);
0
 
dutaAuthor Commented:
Dear Matthew:

Thanks a lot.

By the way, I wonder whether I may use IgnoreCase or ToLowerCase.

Thanks!
0
 
dutaAuthor Commented:
When I tried John, john, King, and king, they were sorted not as I expected.

Thanks!
0
 
matthew016Commented:
Case sensitive :
java.util.Arrays.sort(myArray);

Case insensitive :
java.util.Arrays.sort(myArray, String.CASE_INSENSITIVE_ORDER);
0
 
matthew016Commented:
For more professional code, be more oriented objected.

Create a class Client, create a class that contains a list of Clients, and a Test class.
Maybe it is a bit too much for this simple code.

For example :
*************************************************************
public class Client {
      private String name;
      
      public Client(String name) {
            this.name = name;
      }
      public String getName() {
            return name;
      }
      public String toString() {
            return name;
      }
}
*************************************************************
import java.util.ArrayList;
import java.util.Collections;

public class Clients {
        private ArrayList clients;
        
        public Clients() {
              clients = new ArrayList();
        }
        public void addClient(Client client) {
              clients.add(client);
        }
        public ArrayList getClients () {
                return clients;    
        }
        public void sortNames () {
          Collections.sort(clients);
        }
}
*************************************************************
import javax.swing.JOptionPane;

public class Test {
        public static int MAX = 7;
        private Clients clients;
        
        public Test() {
              makeClients();
              sortClients();
              displayClients();
        }
        private void makeClients () {
            clients = new Clients();
          for (int i = 0; i < MAX; i++ ) {
             Client client = new Client(getInput ("Enter a name."));  
                                            // get seven names from users.
             clients.addClient(client);
           }
        }
        private String getInput (String msg) {
              return JOptionPane.showInputDialog (msg);
        }
        private void sortClients() {
              clients.sortNames();
        }
        private void displayClients () {
           JOptionPane.showMessageDialog (null, clients.getClients());
        }
        public static void main (String[] args) {
            new Test();
        }
}
0
 
dutaAuthor Commented:
Dear Matthew:

I tried as the follows, but I got some error messages.

Thanks again!

_____________________________   The modified area __________________________


public void sortNames ( )
  {
    String [ ] names = getNames ( );  
 
   //  Arrays.sort(names);
   
   java.util.Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);  // This is a new addition

   
    display (names);
    JOptionPane.showMessageDialog
                     (null, "The fist name is " 
                          + names [0]
                          + ".\n The last name is " 
                          +names [names.length - 1] );
       
  }
0
 
matthew016Commented:
What is the error ?

Why can't u debug that yourself ?
0
 
dutaAuthor Commented:
Sorry to bother you too much.

I asked you because I could not do it.

I think you did enough for me tonight. Regardless of answering my last question, I am going to accept your tip as acceptable solution.

Thanks again!
0
 
matthew016Commented:
Hey duta, u are not bothering me at all !!!

I want to help u and know why u can't see the new problem by yourself !!!

If u can see your problems everything will be much easier !

My last comment could be interpreted differently, sorry !
0
 
dutaAuthor Commented:
The error message was :

"cannot find
symbol
variable util
Location: class Java

Thanks!
0
 
matthew016Commented:
ok, I think that's because u imported java.util

and u put in the code :

 java.util.Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);

If u imported java.util u just need to code this :

Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
0
 
dutaAuthor Commented:
Thank so much for helping me out so kindly and patiently.

It works just great.

I am a real beginner, but I am working hard to learn.

Thanks again!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.