Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

num 2 I have a program for a phone directory. It needs to add, delete, append, a

ID: 3558622 • Letter: N

Question

num 2

I have a program for a phone directory. It needs to add, delete, append, and edit telephone records. I've gotten it to write and search the files. Just need to get it to delete and edit them.

Here's what I have so far:


import java.nio.file.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Roladex extends JFrame implements ActionListener {

Path filename = Paths.get("C:\Users\Jeremiah\Documents\CIS-210\test\phoneBook.txt");
String s = "00, , ,"
+ " , , , " + System.getProperty("line.separator");
final int RECSIZE = s.length();
FileChannel fc = null;
String delimiter = ",";
String file[] = new String[100];
String nme;
String addrss;
String cy;
String stte;
String zippy;
String phne;

final int W = 500;
final int H = 700;
int count = 0;

ImageIcon icon = new ImageIcon("C:\Users\Jeremiah\Documents\CIS-210\phoneBook.jpg");

JLabel label = new JLabel(icon);

//panels for rows
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JPanel row3 = new JPanel();
JPanel row4 = new JPanel();
JPanel row5 = new JPanel();
JPanel row6 = new JPanel();
JPanel row7 = new JPanel();
JPanel row8 = new JPanel();
JPanel row9 = new JPanel();

//panel for field
JPanel fieldPanel = new JPanel();
//labels
JLabel nm = new JLabel("NAME--------");
JTextField name = new JTextField(15);
JLabel ad = new JLabel("ADDRESS-");
JTextField address = new JTextField(15);
JLabel cty = new JLabel("CITY----------");
JTextField city = new JTextField(15);
JLabel st = new JLabel("STATE------");
JTextField state = new JTextField(2);
JLabel zp = new JLabel("ZIP------------");
JTextField zip = new JTextField(5);
JLabel ph = new JLabel("PHONE #---");
JTextField phone = new JTextField(12);

//buttons
JButton add = new JButton("Add new contact");
JButton delete = new JButton("Delete contact");
JButton edit = new JButton("Edit contact");
JButton search = new JButton("Search for contact");

//display
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "The UI manager could not set the Look and Feel for this app.", "Error",
JOptionPane.INFORMATION_MESSAGE);
}
{
Roladex f = new Roladex();
f.setVisible(true);
f.setTitle("Roladex");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(true);
f.setLocation(200, 200);
}
}

public Roladex() {
//construct container
Container c = getContentPane();
c.setLayout((new BorderLayout()));

fieldPanel.setLayout(new GridLayout(15, 1));

FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT, 5, 3);
FlowLayout rowSet = new FlowLayout(FlowLayout.CENTER, 5, 3);
row1.setLayout(rowSet);
row2.setLayout(rowSetup);
row3.setLayout(rowSetup);
row4.setLayout(rowSetup);
row5.setLayout(rowSetup);
row6.setLayout(rowSetup);
row7.setLayout(rowSetup);
row8.setLayout(rowSetup);
row9.setLayout(rowSetup);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
nm.setFont(new Font("Arial", Font.BOLD, 16));
ad.setFont(new Font("Arial", Font.BOLD, 16));
cty.setFont(new Font("Arial", Font.BOLD, 16));
st.setFont(new Font("Arial", Font.BOLD, 16));
zp.setFont(new Font("Arial", Font.BOLD, 16));
ph.setFont(new Font("Arial", Font.BOLD, 16));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(W, H);
setLayout(new FlowLayout());
JLabel heading = new JLabel("PHONE DIRECTORY");
heading.setForeground(Color.RED);
heading.setFont(new Font("Arial", Font.BOLD, 22));
//add components

row1.add(heading);
add(heading, BorderLayout.NORTH);
heading.setVisible(true);
add(label, BorderLayout.CENTER);
label.setVisible(true);
row2.add(nm);
nm.setVisible(true);
row2.add(name);
name.setVisible(true);
row3.add(ad);
ad.setVisible(true);
row3.add(address);
address.setVisible(true);
row4.add(cty);
cty.setVisible(true);
row4.add(city);
city.setVisible(true);
row5.add(st);
st.setVisible(true);
row5.add(state);
state.setVisible(true);
row6.add(zp);
zp.setVisible(true);
row6.add(zip);
zip.setVisible(true);
row7.add(ph);
ph.setVisible(true);
row7.add(phone);
phone.setVisible(true);
row8.add(add);
row8.add(delete);
row8.add(edit);
row8.add(search);

//add rows to panel
fieldPanel.add(row1);
fieldPanel.add(row2);
fieldPanel.add(row3);
fieldPanel.add(row4);
fieldPanel.add(row5);
fieldPanel.add(row6);
fieldPanel.add(row7);
fieldPanel.add(row8);

c.add(fieldPanel, BorderLayout.CENTER);

//add listeners
add.addActionListener(this);
edit.addActionListener(this);
delete.addActionListener(this);
search.addActionListener(this);
}

@Override
@SuppressWarnings("empty-statement")
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();

if (add == source) {
if (checkFields()) {
try {
OutputStream output = new BufferedOutputStream(Files.newOutputStream(filename, CREATE, APPEND));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));

nme = name.getText();
addrss = address.getText();
cy = city.getText();
stte = state.getText();
zippy = zip.getText();
phne = phone.getText();
s = nme + delimiter + addrss + delimiter + cy + delimiter + stte + delimiter
+ zippy + delimiter + phne + System.getProperty("line.separator");
byte[] data = s.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(data);
writer.write(s, 0, s.length());
writer.close();
} catch (IOException c) {
JOptionPane.showMessageDialog(null, "Whoops!" + c, "Submission UnSucessful",
JOptionPane.INFORMATION_MESSAGE);;
}
}

name.setText("");
address.setText("");
city.setText("");
state.setText("");
zip.setText("");
phone.setText("");
name.requestFocus();

JOptionPane.showMessageDialog(null, "The contact information has been saved!", "Submission Sucessful",
JOptionPane.INFORMATION_MESSAGE);
}
if (search == source) {
int n = 0;
if ("".equals(name.getText())) {
JOptionPane.showMessageDialog(null, "Please enter a name to search for.", "Whoops!",
JOptionPane.INFORMATION_MESSAGE);
} else {
try {
InputStream input = new BufferedInputStream(Files.newInputStream(filename, READ));
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
s = reader.readLine();
boolean f = (false);
while (s != null) {
file[n] = s;
String[] rec = s.split(",");
if (rec[0].equals(name.getText())) {
address.setText(rec[1]);
city.setText(rec[2]);
state.setText(rec[3]);
zip.setText(rec[4]);
phone.setText(rec[5]);
f = (true);
}
s = reader.readLine();
}
if (!f) {
JOptionPane.showMessageDialog(null, "No such file", "Whoops!",
JOptionPane.INFORMATION_MESSAGE);
}
reader.close();
} catch (IOException c) {
JOptionPane.showMessageDialog(null, "Whoops!" + c, "No file exists",
JOptionPane.INFORMATION_MESSAGE);
}

}
}

//I know I'm going to have to search the records in order to edit/delete them so
//I copied the search button code here. Need to know how to edit and delete
  
if (source == edit) {
int n = 0;
try {
InputStream input = new BufferedInputStream(Files.newInputStream(filename, READ));
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
s = reader.readLine();
boolean f = (false);
while (s != null) {
file[n] = s;
String[] rec = s.split(",");
if (rec[0].equals(name.getText())) {
address.setText(rec[1]);
city.setText(rec[2]);
state.setText(rec[3]);
zip.setText(rec[4]);
phone.setText(rec[5]);
f = (true);
}
s = reader.readLine();
}
if (!f) {
JOptionPane.showMessageDialog(null, "No such file", "Whoops!",
JOptionPane.INFORMATION_MESSAGE);
}
reader.close();
} catch (IOException c) {
JOptionPane.showMessageDialog(null, "Whoops!" + c, "No file exists",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
public boolean checkFields() {
if ((name.getText().compareTo("") < 1)
|| (address.getText().compareTo("") < 1)
|| (city.getText().compareTo("") < 1)
|| (state.getText().compareTo("") < 1)
|| (zip.getText().compareTo("") < 1)
|| (phone.getText().compareTo("") < 1)) {
JOptionPane.showMessageDialog(null, "You must complete all fields", "Data Entry Error",
JOptionPane.WARNING_MESSAGE);
return false;
} else {
return true;
}
}
}

Explanation / Answer

import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.READ;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;

public class Roladex extends JFrame implements ActionListener {

static List<Person> contactList = new ArrayList<Person>();
Path filename = Paths.get("D:\phoneBook.txt");
String s = "00, , ," + " , , , " + System.getProperty("line.separator");
final int RECSIZE = s.length();
FileChannel fc = null;
String delimiter = ",";
String file[] = new String[100];
String nme;
String addrss;
String cy;
String stte;
String zippy;
String phne;

final int W = 500;
final int H = 700;
int count = 0;

ImageIcon icon = new ImageIcon(
   "C:\Users\Jeremiah\Documents\CIS-210\phoneBook.jpg");

JLabel label = new JLabel(icon);

// panels for rows
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JPanel row3 = new JPanel();
JPanel row4 = new JPanel();
JPanel row5 = new JPanel();
JPanel row6 = new JPanel();
JPanel row7 = new JPanel();
JPanel row8 = new JPanel();
JPanel row9 = new JPanel();

// panel for field
JPanel fieldPanel = new JPanel();
// labels
JLabel nm = new JLabel("NAME--------");
JTextField name = new JTextField(15);
JLabel ad = new JLabel("ADDRESS-");
JTextField address = new JTextField(15);
JLabel cty = new JLabel("CITY----------");
JTextField city = new JTextField(15);
JLabel st = new JLabel("STATE------");
JTextField state = new JTextField(2);
JLabel zp = new JLabel("ZIP------------");
JTextField zip = new JTextField(5);
JLabel ph = new JLabel("PHONE #---");
JTextField phone = new JTextField(12);

// buttons
JButton add = new JButton("Add new contact");
JButton delete = new JButton("Delete contact");
JButton edit = new JButton("Edit contact");
JButton search = new JButton("Search for contact");
JButton save = new JButton("Save Edited contact");

// display
public static void main(String[] args) {
  try {
   UIManager
     .setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
  } catch (Exception e) {
   JOptionPane
     .showMessageDialog(
       null,
       "The UI manager could not set the Look and Feel for this app.",
       "Error", JOptionPane.INFORMATION_MESSAGE);
  }
  {
   Roladex f = new Roladex();
   f.setVisible(true);
   f.setTitle("Roladex");
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setResizable(true);
   f.setLocation(200, 200);
  }
}

public Roladex() {
  // construct container
  readFromFile();
  Container c = getContentPane();
  c.setLayout((new BorderLayout()));

  fieldPanel.setLayout(new GridLayout(15, 1));

  FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT, 5, 3);
  FlowLayout rowSet = new FlowLayout(FlowLayout.CENTER, 5, 3);
  row1.setLayout(rowSet);
  row2.setLayout(rowSetup);
  row3.setLayout(rowSetup);
  row4.setLayout(rowSetup);
  row5.setLayout(rowSetup);
  row6.setLayout(rowSetup);
  row7.setLayout(rowSetup);
  row8.setLayout(rowSetup);
  row9.setLayout(rowSetup);

  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  nm.setFont(new Font("Arial", Font.BOLD, 16));
  ad.setFont(new Font("Arial", Font.BOLD, 16));
  cty.setFont(new Font("Arial", Font.BOLD, 16));
  st.setFont(new Font("Arial", Font.BOLD, 16));
  zp.setFont(new Font("Arial", Font.BOLD, 16));
  ph.setFont(new Font("Arial", Font.BOLD, 16));
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setSize(W, H);
  setLayout(new FlowLayout());
  JLabel heading = new JLabel("PHONE DIRECTORY");
  heading.setForeground(Color.RED);
  heading.setFont(new Font("Arial", Font.BOLD, 22));
  // add components

  row1.add(heading);
  add(heading, BorderLayout.NORTH);
  heading.setVisible(true);
  add(label, BorderLayout.CENTER);
  label.setVisible(true);
  row2.add(nm);
  nm.setVisible(true);
  row2.add(name);
  name.setVisible(true);
  row3.add(ad);
  ad.setVisible(true);
  row3.add(address);
  address.setVisible(true);
  row4.add(cty);
  cty.setVisible(true);
  row4.add(city);
  city.setVisible(true);
  row5.add(st);
  st.setVisible(true);
  row5.add(state);
  state.setVisible(true);
  row6.add(zp);
  zp.setVisible(true);
  row6.add(zip);
  zip.setVisible(true);
  row7.add(ph);
  ph.setVisible(true);
  row7.add(phone);
  phone.setVisible(true);
  row8.add(add);
  row8.add(delete);
  row8.add(edit);
  row8.add(search);

  // add rows to panel
  fieldPanel.add(row1);
  fieldPanel.add(row2);
  fieldPanel.add(row3);
  fieldPanel.add(row4);
  fieldPanel.add(row5);
  fieldPanel.add(row6);
  fieldPanel.add(row7);
  fieldPanel.add(row8);
  fieldPanel.add(row9);

  c.add(fieldPanel, BorderLayout.CENTER);

  // add listeners
  add.addActionListener(this);
  edit.addActionListener(this);
  delete.addActionListener(this);
  search.addActionListener(this);
  save.addActionListener(this);
}

@Override
@SuppressWarnings("empty-statement")
public void actionPerformed(ActionEvent e) {
  Object source = e.getSource();

  if (add == source) {
   addRecord();
  }
  if (search == source) {
   
   searchRecord();
  }

  // I know I'm going to have to search the records in order to
  // edit/delete them so
  // I copied the search button code here. Need to know how to edit and
  // delete

  if (source == edit) {
   
   int i=searchRecord();
   contactList.remove(i);
   fieldPanel.remove(row8);
   row9.add(save);
   validate();
  }
  
  if (source == save) {
   
   addRecord();
   fieldPanel.add(row8);
   fieldPanel.remove(row9);
   JOptionPane.showMessageDialog(null,"Saved Successfully");
   validate();
  }

  if (source == delete) {
   if ("".equals(name.getText())) {
    JOptionPane.showMessageDialog(null,
      "Please enter a name to search for.", "Whoops!",
      JOptionPane.INFORMATION_MESSAGE);
   } else {
    boolean isDeleted = false;
    for (int i = 0; i < contactList.size(); i++) {
     Person p = contactList.get(i);
     if (p.getName().equals(name.getText())) {
      contactList.remove(i);
      isDeleted = true;
      break;
     }
    }

    if (isDeleted) {
     JOptionPane.showMessageDialog(null, "Successfully Deleted");
    } else {
     JOptionPane.showMessageDialog(null,
       "No Record Found With Name " + name.getText());
    }
    name.setText("");
    address.setText("");
    city.setText("");
    state.setText("");
    zip.setText("");
    phone.setText("");
    name.requestFocus();
    writeToFile();
   }
  }

}

public boolean checkFields() {
  if ((name.getText().compareTo("") < 1)
    || (address.getText().compareTo("") < 1)
    || (city.getText().compareTo("") < 1)
    || (state.getText().compareTo("") < 1)
    || (zip.getText().compareTo("") < 1)
    || (phone.getText().compareTo("") < 1)) {
   JOptionPane.showMessageDialog(null, "You must complete all fields",
     "Data Entry Error", JOptionPane.WARNING_MESSAGE);
   return false;
  } else {
   return true;
  }
}

public void writeToFile() {

  try {
   OutputStream output = new BufferedOutputStream(
     Files.newOutputStream(filename, TRUNCATE_EXISTING));

   output = new BufferedOutputStream(Files.newOutputStream(filename,
     CREATE));

   BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
     output));
   for (int i = 0; i < contactList.size(); i++) {
    Person person = contactList.get(i);
    s = person.getName() + delimiter + person.getAddress()
      + delimiter + person.getCity() + delimiter
      + person.getState() + delimiter + person.getZip()
      + delimiter + person.getPhone()
      + System.getProperty("line.separator");
    byte[] data = s.getBytes();
    ByteBuffer buffer = ByteBuffer.wrap(data);
    writer.write(s, 0, s.length());
   }
   writer.close();
  } catch (IOException c) {
   JOptionPane.showMessageDialog(null, "Whoops!" + c,
     "Submission UnSucessful", JOptionPane.INFORMATION_MESSAGE);
   ;
  }

}

public void readFromFile() {
  try {
   InputStream input = new BufferedInputStream(Files.newInputStream(
     filename, READ));
   BufferedReader reader = new BufferedReader(new InputStreamReader(
     input));
   s = reader.readLine();
   boolean f = (false);
   while (s != null) {
    String[] rec = s.split(",");
    Person person = new Person(rec[0], rec[1], rec[2], rec[3],
      rec[4], rec[5]);
    contactList.add(person);
    s = reader.readLine();
   }

   reader.close();
  } catch (IOException c) {
   JOptionPane
     .showMessageDialog(
       null,
       "Whoops! No contacts Added Till now ! Click Ok to Add contacts",
       "No Contacts", JOptionPane.INFORMATION_MESSAGE);
  }
}

public int searchRecord()
{

  int i = 0;
  if ("".equals(name.getText())) {
   JOptionPane.showMessageDialog(null,
     "Please enter a name to search for.", "Whoops!",
     JOptionPane.INFORMATION_MESSAGE);
  }
  
  else {
   
   boolean isFound = false;
   for ( i = 0; i < contactList.size(); i++) {
    Person p = contactList.get(i);
    if (p.getName().equals(name.getText())) {
     isFound = true;
     break;
    }
   }

   if (isFound) {
    Person person = contactList.get(i);
    name.setText(person.getName());
    address.setText(person.getAddress());
    city.setText(person.getCity());
    state.setText(person.getState());
    zip.setText(person.getZip());
    phone.setText(person.getPhone());
    name.requestFocus();
   } else {
    JOptionPane.showMessageDialog(null,
      "No Record Found With Name " + name.getText());
   }
  }
  return i;
}

public void addRecord()
{

  if (checkFields()) {
   nme = name.getText();
   addrss = address.getText();
   cy = city.getText();
   stte = state.getText();
   zippy = zip.getText();
   phne = phone.getText();

   Person person = new Person(nme, addrss, cy, stte, zippy, phne);
   contactList.add(person);

   writeToFile();
  }

  name.setText("");
  address.setText("");
  city.setText("");
  state.setText("");
  zip.setText("");
  phone.setText("");
  name.requestFocus();

  JOptionPane.showMessageDialog(null,
    "The contact information has been saved!",
    "Submission Sucessful", JOptionPane.INFORMATION_MESSAGE);

}
}