Solved

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

Posted on 2006-10-30
16
278 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
ID: 17838789
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
ID: 17838808
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
ID: 17838851
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
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 

Author Comment

by:duta
ID: 17838896
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
ID: 17838919
JOptionPane.showMessageDialog (null, names[0]+"\n"+names[names.length-1]);
0
 

Author Comment

by:duta
ID: 17838954
Dear Matthew:

Thanks a lot.

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

Thanks!
0
 

Author Comment

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

Thanks!
0
 
LVL 9

Expert Comment

by:matthew016
ID: 17838966
Case sensitive :
java.util.Arrays.sort(myArray);

Case insensitive :
java.util.Arrays.sort(myArray, String.CASE_INSENSITIVE_ORDER);
0
 
LVL 9

Expert Comment

by:matthew016
ID: 17838994
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
ID: 17839000
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
ID: 17839009
What is the error ?

Why can't u debug that yourself ?
0
 

Author Comment

by:duta
ID: 17839020
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
ID: 17839030
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
ID: 17839031
The error message was :

"cannot find
symbol
variable util
Location: class Java

Thanks!
0
 
LVL 9

Expert Comment

by:matthew016
ID: 17839040
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
ID: 17839064
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

Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Java Jpanels and Jframe 8 33
split string containing \r\n in Java 46 44
ForLoop Example 3 49
Opening PDF on button click and fill new document 2 38
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

809 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