Solved

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

Posted on 2006-10-30
16
270 Views
Last Modified: 2008-02-01
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);    
  }
 
 
 
 
}
 
 
   
   
 
 
0
Comment
Question by:duta
  • 9
  • 7
16 Comments
 
LVL 9

Accepted Solution

by:
matthew016 earned 500 total points
Comment Utility
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
 
LVL 9

Expert Comment

by:matthew016
Comment Utility
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
 
LVL 9

Expert Comment

by:matthew016
Comment Utility
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
 

Author Comment

by:duta
Comment Utility
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
 
LVL 9

Expert Comment

by:matthew016
Comment Utility
JOptionPane.showMessageDialog (null, names[0]+"\n"+names[names.length-1]);
0
 

Author Comment

by:duta
Comment Utility
Dear Matthew:

Thanks a lot.

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

Thanks!
0
 

Author Comment

by:duta
Comment Utility
When I tried John, john, King, and king, they were sorted not as I expected.

Thanks!
0
 
LVL 9

Expert Comment

by:matthew016
Comment Utility
Case sensitive :
java.util.Arrays.sort(myArray);

Case insensitive :
java.util.Arrays.sort(myArray, String.CASE_INSENSITIVE_ORDER);
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 9

Expert Comment

by:matthew016
Comment Utility
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
 

Author Comment

by:duta
Comment Utility
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
 
LVL 9

Expert Comment

by:matthew016
Comment Utility
What is the error ?

Why can't u debug that yourself ?
0
 

Author Comment

by:duta
Comment Utility
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
 
LVL 9

Expert Comment

by:matthew016
Comment Utility
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
 

Author Comment

by:duta
Comment Utility
The error message was :

"cannot find
symbol
variable util
Location: class Java

Thanks!
0
 
LVL 9

Expert Comment

by:matthew016
Comment Utility
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
 

Author Comment

by:duta
Comment Utility
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

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This video teaches viewers about errors in exception handling.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now