// Guide to Data Structures
// Section 11.7
// Copyright 2018, by J.T. Streib and T. Soma
import javax.swing.*;
import java.util.*;
class EquineDB {
public static void main(String[] args) {
HashMap horseMap = new HashMap();
char option;
do {
option = getOption();
switch(option) {
case 'A': add(horseMap);
break;
case 'D': delete(horseMap);;
break;
case 'S': search(horseMap);;
break;
case 'P': print(horseMap);;
break;
}
} while(option != 'Q');
System.exit(0);
}
private static char getOption() {
char option;
String str;
str = "Welcome to Equine Database\n"
+ "A. Add\n"
+ "D. Delete\n"
+ "S. Search\n"
+ "P. Print\n"
+ "Q. Quit\n"
+ "\nEnter A, D, S, P or Q:\n";
option = JOptionPane.showInputDialog(null, str).charAt(0);
return option;
}
private static void add(HashMap horseMap) {
int id;
String name, breed;
id = Integer.parseInt(JOptionPane.showInputDialog(null,
"Enter ID number: "));
name = JOptionPane.showInputDialog(null, "Enter name: ");
breed = JOptionPane.showInputDialog(null, "Enter breed: ");
horseMap.put(id, new Horse(name, breed));
}
private static void delete(HashMap horseMap) {
int id;
id = Integer.parseInt(JOptionPane.showInputDialog(null,
"Enter ID number: "));
horseMap.remove(id);
}
private static void search(HashMap horseMap) {
int id;
id = Integer.parseInt(JOptionPane.showInputDialog(null,
"Enter ID number: "));
JOptionPane.showMessageDialog(null, "ID " + id + " belongs to "
+ horseMap.get(id));
}
private static void print(HashMap horseMap) {
String str = "";
Set<Integer> keys = horseMap.keySet();
for(Integer id:keys)
str = str + "ID " + id + " belongs to "
+ horseMap.get(id) + "\n";
JOptionPane.showMessageDialog(null, str);
}
}
public class Horse {
private String name, breed;
public Horse(String name, String breed) {
this.name = name;
this.breed = breed;
}
public String getName() {
return name;
}
public String getBreed() {
return breed;
}
public void setName(String name) {
this.name = name;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String toString() {
return (name + ", " + breed);
}
public int hashCode() {
int hashcode = 0;
for(int i=0; i<name.length(); i++)
hashcode = hashcode + name.charAt(i);
return hashcode;
}
public boolean equals(Object obj) {
boolean result = false;
Horse otherHorse = (Horse) obj;
if(otherHorse.name.equals(this.name)
&& otherHorse.breed.equals(this.breed))
result = true;
return result;
}
}