Some help with java programming

Associate
Joined
10 Oct 2005
Posts
283
Location
Liverpool, UK
ok, so i have a small project to work on, using java to make a small application that reads from an external data file.

i need help sorting out a menu system and some operations for the application to run, as i am terrible at programming!

so far my code will read the file when you type in the name, then letyou save it with a new name.

next i need to work on getting the application to display the information (name, phone number, email).

after i do this, i will move onto stuff like getting it to order the information, adding and deleting information and saving it.

if you cant offer direct help, links to websites are very welcome.

thanks
 
Well you got two ways of displaying the information really... either by GUI or by console..

Roughly speaking, do input output, process data, display data. To sort the information you need to really hold your data read in from the file in some data structure. Look at java collections for this.

http://java.sun.com/docs/books/tutorial/collections/implementations/index.html

You could also just use simple arrays of objects... choose the right structure for the job.
 
I would have an object for each person added to your contact list and some sort of data structure to hold all the contacts. Then to add a new record all you would do would be create the object and enter it into the contact list. I would use a TreeSet to hold the contants in order (prolly alphabetically).

To display the contact you can just then call a print out method on that object.

Then to give the option to save you can just dump the object to a file or write it to a file as text.

I doubt anyone is going to write the code for you though.
 
you could save an ArrayList of Detail Objects (Detail class includes name, no, address) to a file

Adding :
creating new Detail Object then add it to the ArrayList and overwrite the file with the updated ArrayList

Ordering :
Implement the Comparable interface in the Detail class and implement the compareTo() method and in it compare the name Strings to order alphabetically. Then you can sort by name etc using the Collections.sort(ArrayList) method

Deleting :
as long as you overide the equals() method in the Detail class you can simply delete the object from the ArrayList

Displaying:
Read the ArrayList from the file, and then you can display the contents of that ArrayList in several ways.

GUI:
you really need to explain how you want it too look and work like inorder for me to give you advice on that, but overiding the Detail class toString() method is good idea if you want to print details on screen, or display details in a list etc.

Also remember that any class which you intend to write to a file needs to implement the Serializable interface
thats how i would first attemp all that anyway :P
 
Last edited:
i understand roughly what your saying guys, but i really havent a clue on how to implement it.

i got a ton of help from my mate, and my code thus far is this:

Code:
import java.util.*;
import java.io.PrintStream;
import java.io.File;
import java.io.FileNotFoundException;

public class contacts
{
    private static final int MAX_RECORDS = 20;
    private static String lastName[] = new String[MAX_RECORDS];
    private static String firstName[] = new String[MAX_RECORDS];
    private static String telNumber[] = new String[MAX_RECORDS];
    private static String emailAddress[] = new String[MAX_RECORDS];
    private static Scanner data_input = new Scanner(System.in);
    
    public static int read_in_file(String file_name)
    {
        Scanner read_in;
        Scanner line;
        int record_count = 0;
        String record;
        
        try
        {
            read_in = new Scanner(new File(file_name));
            
            // read in one line at a time
            read_in.useDelimiter(System.getProperty("line.separator")); 
            while (read_in.hasNext())
            {
                // Test to see if there are too many records in the file
                if (record_count == MAX_RECORDS)
                {
                    System.out.printf("Only %d records allowed in file", MAX_RECORDS);
                    System.exit(0);
                }
                
                // read in record
                record = new String(read_in.next());
                
                // Split the record up into its fields and store in
                // appropriate arrays
                line = new Scanner(record);
                line.useDelimiter("\\s*,,\\s*");
                lastName[record_count] = line.next();
                firstName[record_count] = line.next();
                telNumber[record_count] = line.next();
                emailAddress[record_count] = line.next();
            
                // Increment record count
                record_count++;
            }
        }
        catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        
        }
        return record_count;
    }
    
    public static void write_out_file(int no_of_records, String filename)
    {
        PrintStream write_out;
        int counter;
        
        try
        {
            // Create new file
            write_out = new PrintStream(new File(filename));
            
            // Output all reacords
            for(counter = 0; counter < no_of_records; counter++)
            {
                // Output a record
                write_out.print(lastName[counter]);
                write_out.print(",,");
                write_out.print(firstName[counter]);
                write_out.print(",,");
                write_out.print(telNumber[counter]);
                write_out.print(",,");
                write_out.println(emailAddress[counter]);
            }
            
            // Close file
            write_out.close();
        }
        catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        }
    }
    
    // Your 'Methods' go here
    public static void main(String[] args)
    {   
        
        // Declare Variables
        int user_choice;
        boolean quit = false;
        Scanner dataInput = new Scanner(System.in);
        int number_of_records, records, n, sort;
        String filename, first_name, last_name, enter, tel_num, email_addr;
        
        // Get filename and read in file
        System.out.print("Enter the masterfile file name: ");
        filename = data_input.next();
        number_of_records = read_in_file(filename);
        
        // Your 'main' code goes here

        //display menu
        do
        {
        System.out.printf("%n%nMenu%n%n");
        System.out.println("1. Search records (use * to list all)");
        System.out.println("2. Insert record");
        System.out.println("3. Delete record");
        System.out.println("4. Quit with saving");
        System.out.println("5. Quit without saving");

        //get users choice
        user_choice = data_input.nextInt();

        //process choice
        switch(user_choice)
        {
            case 1:
               	{
					System.out.print("Please Enter Last Name: ");
					last_name = dataInput.next();
					System.out.print("Do You with to Enter First Name? (Y/N): ");
					enter = dataInput.next();
					
					if (enter.equalsIgnoreCase("N"))
					{
						for (int i = 0; i < number_of_records; i++)
						{
							if (last_name.compareTo(lastName[i]) == 0)
								//Arrays.sort(lastName[i]);
							{
								System.out.printf("%n%s%n", 	lastName[i]		);
								System.out.printf("%s%n", 	firstName[i]		);
								System.out.printf("%s%n", 	telNumber[i]		);
								System.out.printf("%s%n", 	emailAddress[i]		);
							}
						}
					}
					if (enter.equalsIgnoreCase("Y"))
					{
						System.out.print("Please Enter First Name: ");
						first_name = dataInput.next();
						for (int i = 0; i < number_of_records; i++)
						{
							if ((last_name.compareTo(lastName[i]) == 0) && (first_name.compareTo(firstName[i]) == 0)) 
							{
								System.out.printf("%n%s%n", 	lastName[i]		);
								System.out.printf("%s%n", 	firstName[i]		);
								System.out.printf("%s%n", 	telNumber[i]		);
								System.out.printf("%s%n", 	emailAddress[i]		);
							}
						}
					}
					if (last_name.compareTo("*") == 0)
					{
						for (int i = 0; i < number_of_records; i++)
							//There cannot be more then a 20 data records in the file
						{
							if (lastName[i] != last_name)
							{
								System.out.printf("%n%s%n", 	lastName[i]		);
								System.out.printf("%s%n", 	firstName[i]		);
								System.out.printf("%s%n", 	telNumber[i]		);
								System.out.printf("%s%n", 	emailAddress[i]		);
							}
						}
					}
				}
                    break;
            case 2:
               {
                System.out.print("Please enter the last name of the contact: ");
                    last_name = dataInput.next();
                    System.out.print("Please enter the first name of the contact: ");
                    first_name = dataInput.next();
                    System.out.print("Please enter the telephone number of the contact: ");
                    tel_num = dataInput.next();
                    System.out.print("Please enter the email address of the contact: ");
                    email_addr = dataInput.next();
                    int z = 0;
                    for (int i=0; i < number_of_records; i++)
                    {
                        if ((last_name.compareTo(lastName[i])) < i && (last_name.compareTo(lastName[i]) > i))
                        {
                            z = i;
                        }
                    }
                    for (int i = number_of_records; i > z; i--)
                    {
                        lastName[i] = lastName[i-1];
                    }
                    lastName[z+1] = last_name;
                    firstName[z+1] = first_name;
                    telNumber[z+1] = tel_num;
                    emailAddress[z+1] = email_addr;
                }
                    break;
            case 3:
            	{
					System.out.print("Please enter the last name of the contact: ");
					last_name = dataInput.next();
					
					int z = 0;
					for (int i=0; i < number_of_records; i++)
					{
						if ((last_name.compareTo(lastName[i])) < i && (last_name.compareTo(lastName[i]) > i))
						{
							z = i;
						}
					}
					for (int i = z; i < number_of_records; i++)
					{
						lastName[i] = lastName[i+1];
					}
					
					// Get new filename and write out the file
					System.out.print("Please Enter New Masterfile File Name: ");
					filename = dataInput.next();
					write_out_file(number_of_records, filename);
					System.out.print("File Save In Progress. Please Wait...");
					for (int r = 0; r < 35000000; ++ r) System.currentTimeMillis ();
					{
						System.out.print("..");
					}
					for (int r = 1000000; r < 10000000; ++ r) System.currentTimeMillis ();
					{
						System.out.print("............");
					}
					System.out.printf("%nGoodbye!");
				}
                    break;
            case 4:
            	{
					// Get new filename and write out the file
					System.out.print("Please Enter New Masterfile File Name: ");
					filename = dataInput.next();
					write_out_file(number_of_records, filename);
					System.out.print("File Save In Progress. Please Wait...");
					for (int r = 0; r < 35000000; ++ r) System.currentTimeMillis ();
					{
						System.out.print("..");
					}
					for (int r = 1000000; r < 10000000; ++ r) System.currentTimeMillis ();
					{
						System.out.print("............");
					}
					System.out.printf("%nGoodbye!");
				}
                    break;
            case 5:
            quit = true;
                    break;
            
            default:
                    System.out.println("Invalid menu choice, please try again");
                }
            } while(!quit);

    }
}

the problem being is that the code is erronous (my mate hasnt gotten any further)

options 1, 4 and 5 work perfectly. option 3 works fine as far as i know. the problem is option 2. you can easily add a new record, e.g. Surname, Name, phone number and email address, but it doesnt add it to the end of the record file as it should do, instead it writes over the second record, and then shifts the surnames of the records below it.

could anyone please help with a solution?
 
i quickly wrote a bit, this way it writes objects to a file instead

it uses a GUI and just adds details to a file, and sorts names alphabetically.

it wouldnt be too hard for you to add delete and file saving functionality

Details.java

Code:
import java.io.*;

public class Details implements Serializable, Comparable{
	private String name, address, phone;

	/**
	 * @param name
	 * @param address
	 * @param phone
	 */
	public Details(String name, String address, String phone) {
		super();
		// TODO Auto-generated constructor stub
		this.name = name;
		this.address = address;
		this.phone = phone;
	}

	/**
	 * @return Returns the address.
	 */
	public String getAddress() {
		return address;
	}

	/**
	 * @param address The address to set.
	 */
	public void setAddress(String address) {
		this.address = address;
	}

	/**
	 * @return Returns the name.
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name The name to set.
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return Returns the phone.
	 */
	public String getPhone() {
		return phone;
	}

	/**
	 * @param phone The phone to set.
	 */
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	public int compareTo(Object that) {
		return this.name.compareTo(((Details)that).name);
	}
	
	public String toString(){
		return name+ " " + phone + " ,   " + address;
	}
	
}
 
Last edited:
FileHandler.java

Code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.*;



public class FileHandler {
	
	public void write(ArrayList a) {
		 try {
	   	      FileOutputStream fout = new FileOutputStream("details.dat");
	   	      ObjectOutputStream oos = new ObjectOutputStream(fout);
	   	      oos.writeObject(a);
	   	      oos.close();
	   	      }
	   	   catch (Exception e) { e.printStackTrace(); }
	}
	
	public ArrayList read() {
		
	 	ArrayList a = new ArrayList();
    	try {
    	    FileInputStream fin = new FileInputStream("details.dat");
    	    ObjectInputStream ois = new ObjectInputStream(fin);
    	    a = (ArrayList) ois.readObject();
    	    ois.close();
    	} catch(Exception e) {}
    	return a;
		
	}
}

GUI.java

Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class GUI extends JFrame{
	private ArrayList contacts;
	private JPanel j1,j2,j3;
	private JList jl;
	private DefaultListModel listM;
	private JTextField t1,t2,t3;
	private JButton add;
	private FileHandler fh;
	
	public GUI() {
		fh = new FileHandler();
		contacts = new ArrayList();
		contacts = fh.read();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		j1 = new JPanel(new GridLayout(1,2));
		jl = new JList(listM = new DefaultListModel());
		j1.add(new JScrollPane(jl));
		j2 = new JPanel(new GridLayout(4,1));
		t1 = new JTextField();
		t2 = new JTextField();
		t3 = new JTextField();
		add = new JButton("Add");
		add.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				Details d = new Details(t1.getText(),t2.getText(),t3.getText());
				System.out.println(d);
				contacts.add(d);
				fh.write(contacts);
				updateContacts(contacts);
			}
		});
		j2.add(t1);
		j2.add(t2);
		j2.add(t3);
		j2.add(add);
		Container c = this.getContentPane();
		j1.add(j2);
		
		c.add(j1);
		this.setSize(500,300);
		updateContacts(contacts);
		this.setVisible(true);
	}
	
	public void updateContacts(ArrayList<Details> a) {
		listM.clear();
		Collections.sort(a);
		for(Details d: a) {
			listM.addElement(d);
		}
	}
	public static void main(String[] args) {
		GUI g = new GUI();
	}
}
 
Last edited:
cheers for the code protocol,im gonna give it a whizz later.

if its not too much trouble,couldyou have a look through the code i posted and try to fix the error in the functions for inserting a new record, as im trying to make it work just with the DOS text window.

thanks again =)
 
Back
Top Bottom