Ok so to give you a brief summary of whats going on our original assignment was to make a password directory that adds, saves, looks up, and removes a name and password that are connected together in an array. So now we need to alter the code so it works with and arraylist instead of an array. We are only changing the ArrayListBasedPasswordDir and PasswordEntry classes because we are given the other three. Here is the code i have as of right now(some parts may be wrong but it was 100% right for the original assignment with just the array)
import java.io.*;
import java.util.*;
/** This is an implementation of the PhoneDirectory interface that uses
* an array to store the data.
* @author Koffman & Wolfgang
*/
public class ArrayListBasedPasswordDir implements PwdDirectory2 {
// Data Fields
/** The initial capacity of the array */
private static final int INITIAL_CAPACITY = 10;
/** The current capacity of the array */
private int capacity = INITIAL_CAPACITY;
/** The current size of the array (number of directory entries) */
private int size = 0;
/** The array to contain the directory data */
private ArrayList<PasswordEntry> theDirectory = new ArrayList<PasswordEntry>();
/** The data file that contains the directory data */
private String sourceName = "pwds.txt";
/** Boolean flag to indicate whether the directory was
modified since it was either loaded or saved. */
private boolean modified = false;
/** Method to load the data file.
pre: The directory storage has been created and it is empty.
If the file exists, it consists of name-number pairs
on adjacent lines.
post: The data from the file is loaded into the directory.
@param sourceName The name of the data file
*/
public void loadData(String sourceName) {
// Remember the source name.
this.sourceName = sourceName;
try {
// Create a BufferedReader for the file.
BufferedReader in = new BufferedReader(
new FileReader(sourceName));
String name;
String pwd;
String num = " ";
// Read each name and number and add the entry to the array.
while ( (num = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(num);
if(st.hasMoreTokens()){
name = st.nextToken();
pwd = st.nextToken();
}
else{
// Read name and number from successive lines.
//if ( (pwd = in.readLine()) == null) {
break; // No number read, exit loop.
}
// Add an entry for this name and number.
add(name, pwd);
}
// Close the file.
in.close();
}
catch (FileNotFoundException ex) {
// Do nothing — no data to load.
return;
}
catch (IOException ex) {
System.err.println("Load of directory failed.");
ex.printStackTrace();
System.exit(1);
}
}
/** Add an entry or change an existing entry.
@param name The name of the person being added or changed
@param number The new number to be assigned
@return The old number or, if a new entry, null
*/
public String addOrChangeEntry(String name, String pwd) {
String oldPassword = null;
int index = theDirectory.indexOf(new PasswordEntry(name," "));
if (index != -1) {
PasswordEntry pE = theDirectory.get(index);
oldPassword = pE.getPassword();
pE.setPassword(pwd);
}
else {
theDirectory.add(new PasswordEntry(name, pwd));
}
modified = true;
return oldPassword;
}
/** Look up an entry.
@param name The name of the person
@return The number. If not in the directory, null is returned
*/
public String lookupEntry(String name) {
int index = theDirectory.indexOf(new PasswordEntry(name," "));
if (index > -1) {
return theDirectory.get(index).getPassword();
}
else {
return null;
}
}
/** Method to save the directory.
pre: The directory has been loaded with data.
post: Contents of directory written back to the file in the
form of name-number pairs on adjacent lines.
modified is reset to false.
*/
public void save() {
if (modified) { // If not modified, do nothing.
try {
// Create PrintWriter for the file.
PrintWriter out = new PrintWriter(
new FileWriter(sourceName));
// Write each directory entry to the file.
for (int i = 0; i < size; i++) {
// Write the name.
out.print(theDirectory.get(i).getName());
out.print(" ");
// Write the number.
out.println(theDirectory.get(i).getPassword());
}
// Close the file and reset modified.
out.close();
modified = false;
}
catch (Exception ex) {
System.err.println("Save of directory failed");
ex.printStackTrace();
System.exit(1);
}
}
}
/** Find an entry in the directory.
@param name The name to be found
@return The index of the entry with the requested name.
If the name is not in the directory, returns -1
*/
private int find(String name) {
for (int i = 0; i < size; i++) {
if (theDirectory.get(i).getName().equals(name)) {
return i;
}
}
return -1; // Name not found.
}
/** Add an entry to the directory.
@param name The name of the new person
@param number The number of the new person
*/
private void add(String name, String pwd) {
theDirectory.add(new PasswordEntry(name, pwd));
}
public boolean isSafe(String pwd){
if(pwd.length() >= 8){
return true;
}
else{
return false;
}
}
public String removeEntry(String name){
int index;
index = find(name);
for(int a = index; a <= size - 1; a++){
theDirectory.remove(index);
}
return name;
}
public String toStirng(){
return null;
}
}
/** The DirectoryEntry contains the name and number, both
* stored as strings. The name is not changable.
* @author Koffman & Wolfgang
*/
public class PasswordEntry {
private String name;
private String pwd;
public PasswordEntry(String name, String pwd){
this.name = name;
this.pwd = pwd;
}
public String getName(){
return name;
}
public String getPassword(){
return pwd;
}
public void setName(String nn){
this.name = nn;
}
public void setPassword(String np){
this.pwd = np;
}
}
import javax.swing.JOptionPane;
/** This class is an implementation of PDUserInterface
* that uses JOptionPane to display the menu of command choices.
* @author Koffman & Wolfgang
*/
public class PDGUI2 implements PDUserInterface2 {
/** A reference to the PasswordDirectory object to be processed.
Globally available to the command-processing methods.
*/
private PwdDirectory2 theDirectory = null;
private long elapsed;
// Methods
/** Method to display the command choices and process user
commands.
pre: The directory exists and has been loaded with data.
post: The directory is updated based on user commands.
@param thePhoneDirectory A reference to the PhoneDirectory
to be processed
*/
public void processCommands(PwdDirectory2 thePWDirectory) {
String[] commands = {
"Runtime",
"Show All",
"Add/Change Entry",
"Look Up Entry",
"Remove Entry",
"Save Directory",
"Exit"};
theDirectory = thePWDirectory;
int choice;
do {
choice = JOptionPane.showOptionDialog(
null, // No parent
"Select a Command", // Prompt message
"PasswordDirectory", // Window title
JOptionPane.YES_NO_CANCEL_OPTION, // Option type
JOptionPane.QUESTION_MESSAGE, // Message type
null, // Icon
commands, // List of commands
commands[commands.length - 1]); // Default choice
switch (choice) {
case 0:
runtimetest();
break;
case 1:
showAll();
break;
case 2:
doAddChangeEntry();
break;
case 3:
doLookupEntry();
break;
case 4:
doRemoveEntry();
break;
case 5:
doSave();
break;
case 6:
break;
default: // Do nothing.
}
}
while (choice != commands.length - 1);
System.exit(0);
}
/** Method to add or change an entry.
pre: The directory exists and has been loaded with data.
post: A new name is added, or the value for the name is
changed, modified is set to true.
*/
private void doAddChangeEntry() {
// Request the name
String newName = JOptionPane.showInputDialog("Enter name");
if (newName == null) {
return; // Dialog was cancelled.
}
// Request the password
String newNumber = JOptionPane.showInputDialog("Enter new password");
if (newNumber == null) {
return; // Dialog was cancelled.
}
String message = null;
// Check for safe password
if (!theDirectory.isSafe(newNumber)) { //password rejected
message = newNumber + "is not a safe password" +
"\nPasswords must contain at least 8 characters" +
"\nand contain at least one numeral.";
}
else {
// Insert/change name-password
String oldNumber = theDirectory.addOrChangeEntry(newName,
newNumber);
if (oldNumber == null) { // New entry.
message = newName + " was added to the directory"
+ "\nwith password: " + newNumber;
}
else { // Changed entry.
message = "Password for " + newName + " was changed "
+ "\nOld password: " + oldNumber
+ "\nNew password: " + newNumber;
}
}
// Display confirmation message.
JOptionPane.showMessageDialog(null, message);
}
/** Method to look up an entry.
pre: The directory has been loaded with data.
post: No changes made to the directory.
*/
private void doLookupEntry() {
// Request the name.
String theName = JOptionPane.showInputDialog("Enter name");
if (theName == null) {
return; // Dialog was cancelled.
}
// Look up the name.
String theNumber = theDirectory.lookupEntry(theName);
String message = null;
if (theNumber != null) { // Name was found.
message = "The password for " + theName + " is " + theNumber;
}
else { // Name was not found.
message = theName + " is not listed in the directory";
}
// Display the result.
JOptionPane.showMessageDialog(null, message);
}
/** Method to remove an entry
Pre: The directory has been loaded with data.
Post: The requested name is removed, modifed is set true
*/
private void doRemoveEntry() {
// Request the name.
String message = null;
String theName = JOptionPane.showInputDialog("Enter name");
theDirectory.removeEntry(theName);
message = theName + " has been removed from the directory";
// Display the result.
JOptionPane.showMessageDialog(null, message);
}
private void runtimetest() {
long startTime = System.currentTimeMillis();
for (int i=0;i<2000;i++)
theDirectory.removeEntry("b");
long stopTime = System.currentTimeMillis();
elapsed = stopTime - startTime;
String message = "runtime to remove 2000 items:" + elapsed + "ms.";
// Display the result.
JOptionPane.showMessageDialog(null, message);
}
/** Method to save the directory to the data file.
pre: The directory has been loaded with data.
post: The current contents of the directory have been saved
to the data file.
*/
private void doSave() {
theDirectory.save();
String message = "The password directory has been saved";
// Display the result.
JOptionPane.showMessageDialog(null, message);
}
private void showAll() {
// Request the name.
String message = theDirectory.toString();
// Display the result.
JOptionPane.showMessageDialog(null, message);
}
public static void main(String[] args){
// Is Eclipse telling you your text file doesn't exist?
// Uncomment the following line and find out where Eclipse is looking for it.
// System.out.println(System.getProperty("user.dir"));
// Then just move your file to that location and you won't get any more file I/O errors.
PDGUI2 gui = new PDGUI2();
PwdDirectory2 ourdir = new ArrayListBasedPasswordDir();
ourdir.loadData("pwds.txt");
gui.processCommands(ourdir);
}
}
public interface PDUserInterface2 {
/** Abstract method that processes user's commands.
@param thePhoneDirectory The PhoneDirectory object that
contains the data to be displayed and/or changed
*/
void processCommands(PwdDirectory2 thePwdDirectory);
}
public interface PwdDirectory2 {
/** Load the data file containing the directory.
*
* @param sourcename The name of the file with the password directory entries
*/
void loadData(String sourcename);
/** Look up an entry.
*
* @param name The userid
* @return The password or null if name is not in the directory
*/
String lookupEntry(String name);
/** Add an entry or change an existing entry.
*
* @param name The userid of the entry being added or changed
* @param pwd The new password being assigned
* @return The old password, or if this is a new entry, null
*/
String addOrChangeEntry(String name, String pwd);
/** Remove an entry from the directory.
*
* @param name The userid of the entry to be removed
* @return The current password, or if not in the directory, null
*/
String removeEntry(String name);
/** Method write the current directory to file.
* pre: The directory contains data
* post: Contents of the directory written back to file in the form of userid-password pairs,
* one paired entry per line with a space separating the userid and the password.
* modified is reset to false.
*/
void save();
boolean isSafe(String pswd);
/** Check a password string to see if it is secure
*
* @param pswd A proposed password
* @return true if the password is secure, else false
*/
String toString();
/** produce a String representation of a list-based directory
*
* @return a representation of the list
*/
}