How to finish this Java classes assignment? - java

Here is my assignment:
Create a class that contains an address book entry and name it AddressBook. The table below describes the information that an address book entry has. Name, Address, Mobile Number, Email Address.
Here is my code, I am not sure if it's correct:
public class AddressBook {
private String name;
private String address;
private int mobilenumber;
private String emailaddress;
public AddressBook(){}
public AddressBook (String name, String address,
int mobilenumber, String emailaddress){
this.name = name;
this.address = address;
this.mobilenumber = mobilenumber;
this.emailaddress = emailaddress;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address = address;
}
public int getMobileNumber(){
return mobilenumber;
}
public void setMobileNumber(int mobilenumber){
this.mobilenumber = mobilenumber;}
public String getEmailAddress(){
return emailaddress;
}
public void setEmailAddress(String emailaddress){
this.emailaddress = emailaddress;
}
public String toString(){
return "Name: " + name + "Address: " + address +
"Mobile Number: " + mobilenumber + "Email Address: " + emailaddress;
}
}
Here is the next part of the assignment:
Create a class and name it AddressBookTest which will contain the main method for implementation of the AddressBook class methods from #1 of this activity. Instantiate an array of AddressBook objects of 100 entries. Create a menu that will implement the following methods:
Main Menu
Add Entry
Delete Entry
View All Entries
Update An Entry
Exit
The program should loop back to the main menu after implementing a method chosen by the user. Note that options 2, 3 and 4 should not be implemented if no entry has been added yet. The program ends at the Exit option.
Here my current code, I don't know how to delete, view all or update?
import java.util.Scanner;
public class AddressBookTest {
public static void main(String[] args) {
System.out.println("***PROGRAM INFORMATION*** \nNAME
-> IS THE NAME OF THE PERSON IN THE ADDRESSBOOK \nADDRESS
-> THE ADDRESS OF THE PERSON \nMOBILE NUMBER
-> THE MOBILE NUMBER OF THE PERSON \nEMAIL ADDRESS
-> THE EMAIL ADDRESS OF THE PERSON\n");
String input;
Scanner in = new Scanner(System.in);
AddressBook[] entry = new AddressBook[100];
do
{
System.out.println("Main Menu");
System.out.println("1. Add an Entry");
System.out.println("2. Delete an Entry");
System.out.println("3. View All Entries");
System.out.println("4. Update an Entry");
System.out.println("5. Exit");
System.out.print("Please enter Choices from 1 to 5: ");
input =(in.nextLine());
switch (input) {
case "1":
for(int i = 0; i < 100; i++){
entry[i] = new AddressBook();
System.out.println("***Adding Entry in Address Book***");
System.out.print("First Name: ");
String name = in.next();
System.out.print("Address: ");
String address = in.next();
System.out.print("Mobile Number: ");
int MN = in.nextInt();
System.out.print("Email Address: ");
String EA = in.next();
System.out.println("***Added " + (i+1) + " Entry/Entries\n");
}
break;
case "2":
break;
case "3":
break;
case "4":
break;
default:
break;
}
}while(!input.equals("5"));
System.out.println("***THANK YOU FOR USING MY PROGRAM...***");
}
}

Hopefully this answer helps you with your question:
Here my current code, I don't know how to delete, view all or update?
I really tried to keep it basic, the only new thing introduced is the list instead of an array.
Well first things first, like already said by #daniu. We'll need to change AddressBook to AddressBookEntry, because it really is an entry, not an address book.
AddressBookEntry.java:
package com.kaufland;
//class like it was given
public class AddressBookEntry {
private String name;
private String address;
private int mobilenumber;
private String emailaddress;
public AddressBookEntry() {}
public AddressBookEntry(String name, String address,
int mobilenumber, String emailaddress){
this.name = name;
this.address = address;
this.mobilenumber = mobilenumber;
this.emailaddress = emailaddress;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address = address;
}
public int getMobileNumber(){
return mobilenumber;
}
public void setMobileNumber(int mobilenumber){
this.mobilenumber = mobilenumber;}
public String getEmailAddress(){
return emailaddress;
}
public void setEmailAddress(String emailaddress){
this.emailaddress = emailaddress;
}
public String toString(){
return "Name: " + name + ", Address: " + address +
", Mobile Number: " + mobilenumber + ", Email Address: " + emailaddress;
}
}
Second we need class which represents our AddressBook and contains a List of AddressBookEntries. We chose a List here, because it is easy to extend, which a AdressBook should be.
AdressBook.java:
package com.kaufland;
import java.util.ArrayList;
import java.util.List;
public class AddressBook {
//The diamond operators "<" and ">" specify which type of Objects the List will hold
private List<AddressBookEntry> listOfEntries;
public AddressBook() {
//initialize list of entries
this.listOfEntries = new ArrayList<>();
}
public void add(AddressBookEntry addressBookEntry) {
//List.add adds a new Object to a List
this.listOfEntries.add(addressBookEntry);
}
public void delete(int index) {
//List.remove(int index) removes a object at the given index
this.listOfEntries.remove(index);
}
public AddressBookEntry get(int index) {
//List.get(int index) returns the object at the given index
return this.listOfEntries.get(index);
}
public AddressBookEntry[] viewAll() {
//create a new array with the size of our list
AddressBookEntry[] result = new AddressBookEntry[this.listOfEntries.size()];
//List.toArray(Arr[] array) fills our array with data from the list
this.listOfEntries.toArray(result);
//return the filled array
return result;
}
}
Last we need to apply some changes to your AddressBookTest class, so that we use the functions of our new created AddressBook!
AddressBookTest.java:
package com.kaufland;
import java.util.Scanner;
public class AddressBookTest {
public static void main(String[] args) {
System.out.println("***PROGRAM INFORMATION*** \nNAME" +
"-> IS THE NAME OF THE PERSON IN THE ADDRESSBOOK \nADDRESS" +
"-> THE ADDRESS OF THE PERSON \nMOBILE NUMBER" +
"-> THE MOBILE NUMBER OF THE PERSON \nEMAIL ADDRESS" +
"-> THE EMAIL ADDRESS OF THE PERSON\n");
String input;
Scanner in = new Scanner(System.in);
AddressBook addressBook = new AddressBook();
boolean stop = false;
do
{
System.out.println("\nMain Menu");
System.out.println("1. Add an Entry");
System.out.println("2. Delete an Entry");
System.out.println("3. View All Entries");
System.out.println("4. Update an Entry");
System.out.println("5. Exit");
System.out.print("Please enter Choices from 1 to 5: \n");
input =(in.next());
switch (input) {
case "1":
//create a new entry for the addressbook
AddressBookEntry entry = new AddressBookEntry();
System.out.println("***Adding Entry in Address Book***");
System.out.print("First Name: ");
entry.setName(in.next());
System.out.print("Address: ");
entry.setAddress(in.next());
System.out.print("Mobile Number: ");
entry.setMobileNumber(in.nextInt());
System.out.print("Email Address: ");
entry.setEmailAddress(in.next());
//add our new entry to the addressbook
addressBook.add(entry);
System.out.println("Added a new entry.");
break;
case "2":
System.out.println("Enter the index of the entry, which you want to delete:");
//delete the entry at the given index
addressBook.delete(in.nextInt());
break;
case "3":
System.out.println("Your addressbook contains the following entries:");
//get array of all entries
AddressBookEntry[] listOfEntries = addressBook.viewAll();
//for every entry in the array
for (int i = 0; i < listOfEntries.length; i++) {
System.out.println(listOfEntries[i].toString());
}
break;
case "4":
System.out.println("Enter the index of the entry, which you want to update:");
//get entry at the given index
AddressBookEntry entryToUpdate = addressBook.get(in.nextInt());
System.out.print("First Name (current: " + entryToUpdate.getName() + "):");
entryToUpdate.setName(in.next());
System.out.print("Address: (current: " + entryToUpdate.getAddress() + "):");
entryToUpdate.setAddress(in.next());
System.out.print("Mobile Number: (current: " + entryToUpdate.getMobileNumber() + "):");
entryToUpdate.setMobileNumber(in.nextInt());
System.out.print("Email Address: (current: " + entryToUpdate.getEmailAddress() + "):");
entryToUpdate.setEmailAddress(in.next());
break;
default:
break;
}
//execute while stop is false
} while (!input.equals("5"));
System.out.println("***THANK YOU FOR USING MY PROGRAM...***");
}
}

Related

How can I solve with Java's map containsKey() method?

I checked the code and saving data to the HashMap is correct, when typing ADD. Then after choosing option FIND I can get to the dedicated function but the method is unable to show me found object even if it is correct 100%.
Please check this code out and tell me why it does not find right objects in "public void showInfo(String name, String secondName)" for class Company that is sparked by TYPING "FIND" in class CompanyApp
import java.util.InputMismatchException;
import java.util.Objects;
import java.util.Scanner;
public class CompanyApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
options[] values = options.values();
int choose;
int EXIT_NR = 2;
Company ref = new Company();
do {
System.out.println("Available options: ");
for (options one : values) {
System.out.println(one.getDescription() + " - " + one.name());
}
System.out.println("Choose one: ");
try {
choose = options.valueOf(in.nextLine()).ordinal();
if (Objects.equals(EXIT_NR, choose)) break;
if (choose < 0 || choose >= options.values().length) {
throw new IllegalArgumentException("Choose 0, 1 or 2!");
}
options(choose);
} catch (InputMismatchException e) {
System.out.println("Choose a number ");
}
} while (1 == 1);
}
static void options(int choose){
Company ref = new Company();
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to
find: ");
String secondName2 = info.nextLine();
ref.showInfo(name2, secondName2);
break;
}
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Company {
private Map<String, Employee> map = new HashMap<>();
public void add(Employee employee){
String key = employee.getName() + " " + employee.getSecondName();
if(!map.containsKey(key)){
map.put(key, employee);
System.out.println("Added object to map");}
}
public void showInfo(String name, String secondName){
String key = name + " " + secondName;
System.out.println("in showinfo method");
if(map.containsKey(key)){
System.out.println("found an object");
Employee employee = map.get(key);
System.out.println(employee.getName());
}}}
enum options {
ADD("Add employee "), FIND("Find employee"), EXIT("Exit program");
private String description;
options(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "options{" +
"description='" + description + '\'' +
'}';
}
}
String name;
String secondName;
double salary;
public Employee(String name, String secondName, double salary) {
this.name = name;
this.secondName = secondName;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", secondName='" + secondName + '\'' +
", salary=" + salary +
'}';
}
}
The problem is in the method static void options(int choose). You need to pass the Company-Object and use it there like this:
Call from main method (ref is the Company-Object you create in the main method)
options(choose, ref);
The options-method with the Company as second parameter:
static void options(int choose, Company ref){
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
//use the passed Company here
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to find: ");
String secondName2 = info.nextLine();
//and here
ref.showInfo(name2, secondName2);
break;
}
}
Explanation what is happening in your code
As mentioned, the problem is in the method static void options(int choose).
Here you create a new Company-Object which is not passed in any way to the main method.
This is what happens, when you use ADD and a FIND afterwards:
Call options from main method with ADD
new Company-Object is created in options
new Employee-Object is added to the Company from the previous point
the method ends -> the created Company-Object is "thrown away" (eligible for Garbage Collection)
Call options from main method with FIND
new Company-Object is created in options(therefore no Employees in it)
no Employee can be found, because there is no entry in the map of the newly created Company
The map is empty at the time when you're trying to get the data from it using FIND option. The reason for that is you recreate the Company object in the options method:
Company ref = new Company();
At the same time also the map is recreated so there are no records inside.
Also, the Company object in the main method is not used.

How can I use a string attribute of a class to refer to that class in java?

I have the following 3 classes that is meant to represent a program that allows a user to create a sort of database that can add people and their phone numbers and addresses and then search for them once created.
Here are the classes:
Person
import java.util.*;
public class Person implements Comparable<Person> {
private final String name;
private String street;
private String city;
private String address;
public Person(String name) {
this.name = name;
this.address = "address unknown";
}
public String getName() {
return name;
}
public void setAddress(String street, String city){
this.city = city;
this.street = street;
this.address = this.street + " " + this.city;
}
public String getAddress() {
return address;
}
#Override
public int compareTo(Person o) {
return this.name.compareToIgnoreCase(o.getName());
}
}
PhoneNumbers (to store the person + their phone numbers)
import java.util.*;
import java.util.Collections;
public class PhoneNumbers {
private Map<Person, Set<String>> numbers;
public PhoneNumbers() {
this.numbers = new HashMap<Person, Set<String>>();
}
public void addPhoneNumber(Person person, String phoneNumber){
if(!this.numbers.keySet().contains(person)){
this.numbers.put(person, new HashSet<String>());
}
this.numbers.get(person).add(phoneNumber);
}
public Set<String> searchByPerson(Person person){
if(!this.numbers.keySet().contains(person)){
return this.numbers.get(person);
}
return null;
}
public String searchByNumber(String number){
for(Person person : this.numbers.keySet()){
Set<String> x = this.numbers.get(person);
for(String y : x){
if(y.equals(number)){
return person.getName();
}
}
}
return " not found";
}
public void personalSearch(Person person){
System.out.println(" " + person.getAddress());
if(this.numbers.get(person).size() == 0){
System.out.println(" phone number not found");
}
for(String x : this.numbers.get(person)){
System.out.println(" phone numbers");
System.out.println(" " + x);
}
}
public void remove(Person person){
this.numbers.remove(person);
}
public List<Person> masterSearch(String search){
ArrayList<Person> names = new ArrayList<Person>();
for(Person person : this.numbers.keySet()){
if(person.getName().contains(search) || person.getAddress().contains(search)){
names.add(person);
}
}
Collections.sort(names);
return names;
}
public Map<Person, Set<String>> getNumbers() {
return numbers;
}
}
UI (to provide the way for the user to interact with the program)
import java.util.Scanner;
public class UI {
private Scanner reader;
private PhoneNumbers phoneNumbers;
public UI() {
this.reader = new Scanner(System.in);
this.phoneNumbers = new PhoneNumbers();
}
public void start(){
System.out.println("phone search\n" +
"available operations:\n" +
" 1 add a number\n" +
" 2 search for a number\n" +
" 3 search for a person by phone number\n" +
" 4 add an address\n" +
" 5 search for personal information\n" +
" 6 delete personal information\n" +
" 7 filtered listing\n" +
" x quit\n");
while(true){
System.out.print("command: ");
int command = Integer.parseInt(reader.nextLine());
System.out.println("");
if(command == 1){
System.out.print("whose number: ");
String name = reader.nextLine();
System.out.print("number: ");
String number = reader.nextLine();
Person person = new Person(name);
this.phoneNumbers.addPhoneNumber(person, number);
}
else if(command == 2){
System.out.print("whose number: ");
String person = reader.nextLine();
//something here
}
}
else{
System.out.println(" not found");
}
}
}
}
}
I have a question with the code in the UI specifically
else if(command == 2){
System.out.print("whose number: ");
String person = reader.nextLine();
when the command is given as 2 I ask the user for a name and that is given as a string, how do I then use that String to find the value of the person object with that name under the HashMap i.e. the set of numbers associated with the person.
Obviously I cannot do this with a get method on the map as the keys are person objects not strings and I don't know what to do (do I need to store a map between String name and Person name), I believe in this context names are unique?
Also bonus question: why would I be getting an error when I do command 1 and give a number that is not all digits like "045-4558" for instance.
Thank you
Maybe something like that:
for (Map.Entry<Person, Set<String>> entry : numbers.entrySet()) {
Person key = entry.getKey();
if (key.getName().equals(nameWhichYouAreLookingFor)) {
//Do whatever you want
}
}

Finding and removing a name in an ArrayList

Basically i am trying to search for specif names in an Array-list and then remove just that name.I am doing an assignment for college, and it species to search and remove by name, so i cant use the int index of, I am fairly new to java, so ill post my code maybe I am missing something any help would be great.
import java.util.ArrayList;
public class GaaClub {
private ArrayList<Member> players;
{
}
public GaaClub() {
players = new ArrayList<Member>();
}
public void addStanderedMember() {
// create a message object:
StdOut.println("Please enter the members's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the members address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the members DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the amount to Pay: ");
double mempaid = StdIn.readDouble();
Member player = new Member(name, address, dob, mempaid);
players.add(player);
}
public void addStandaredPlayer() {
// create a message object:
StdOut.println("Please enter the standard Player's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the standard Player's address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the standard Player's DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the amount to Pay: ");
double mempaid = StdIn.readDouble();
StandardPlayer player = new StandardPlayer(name, address, dob, mempaid);
players.add(player);
}
public void addElitePlayer() {
// create a message object:
StdOut.println("Please enter the Elite Players's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the Elite Players's address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the Elite Players's DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the the amount to Pay: ");
double mempaid = StdIn.readDouble();
StdOut.println("Please enter the Elite Players's BMI: ");
double bmi = StdIn.readDouble();
StdOut.println("Please enter the Elite Players's height: ");
double height = StdIn.readDouble();
ElitePlayer player = new ElitePlayer(name, address, dob, mempaid, bmi,
height);
players.add(player);
}
public static void main(String[] args) {
GaaClub app = new GaaClub();
app.run();
}
public void memberType() {
StdOut.println("Enter Type of membership: ");
StdOut.println("1) Add a Standard Member");
StdOut.println("2) Add an Elite Player");
StdOut.println("3) Add a Standard Player");
String memberchoice = StdIn.readString();
if (memberchoice.equals("1"))
addStanderedMember();
if (memberchoice.equals("2"))
addElitePlayer();
if (memberchoice.equals("3"))
addStandaredPlayer();
}
public void listNames() {
for (Member player : players) {
player.list();
}
}
public void removeName() {
for (Member player : players) {
listNames();
String sResponse = StdIn.readString();
if (sResponse.equals(player.name))
{
players.remove(player);;
return;
}
}
}
private int mainMenu() {
StdOut.println("1) Add a Member");
StdOut.println("2) Remove Player");
StdOut.println("3) List Names");
StdOut.println("4) List Members");
StdOut.println("0) Exit");
StdOut.print("==>>");
int option = StdIn.readInt();
return option;
}
public void run() {
{
StdOut.println("Posts");
int option = mainMenu();
while (option != 0) {
switch (option) {
case 1:
memberType();
break;
case 2:
removeName();
break;
case 3:
addStanderedMember();
break;
case 4:
listNames();
break;
}
option = mainMenu();
}
StdOut.println("Exiting...");
}
}
}
And Second file:
import java.util.ArrayList;
public class Member {
protected String name;
protected String address;
protected String dob;
protected double mempaid;
public Member(String name, String address, String dob, double mempaid) {
this.name = name;
this.address = address;
this.dob = dob;
this.mempaid = mempaid ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDob() {
return dob;
}
public void list(){
System.out.println(name);
}
public void setDob(String dob) {
this.dob = dob;
}
public double getMempaid() {
return mempaid;
}
public void setMempaid(double mempaid) {
this.mempaid = mempaid;
}
#Override
public String toString() {
return "Member [name=" + name + ", address=" + address + ", dob=" + dob
+ ", mempaid=" + mempaid + "]";
}
}
import java.util.ArrayList;
public class StandardPlayer extends Member {
private ArrayList<Competition> competition;
public StandardPlayer(String name, String address, String dob,
double mempaid) {
super(name, address, dob, mempaid);
}
public ArrayList<Competition> getCopmetition() {
return competition;
}
public void setCopmetition(ArrayList<Competition> copmetition) {
this.competition = copmetition;
}
void addCompetiton(Competition c) {
}
void payMembership(double amt) {
mempaid = 0;
}
#Override
public String toString() {
return "StandardPlayer [competition=" + competition + ", name=" + name
+ ", address=" + address + ", dob=" + dob + ", mempaid="
+ mempaid + "]";
}
}
And third file:
import java.util.ArrayList;
public class ElitePlayer extends Member {
private double bmi;
private double height;
private ArrayList<Competition> competition;
public ElitePlayer(String name, String address,
String dob, double mempaid, double bmi, double height) {
super(name, address, dob, mempaid);
this.bmi = bmi;
this.height = height;
}
public double getBmi() {
return bmi;
}
public void setBmi(double bmi) {
this.bmi = bmi;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public ArrayList<Competition> getCopmetition() {
return competition;
}
void payMembership(double amt) {
mempaid = 0;
}
#Override
public String toString() {
return "ElitePlayer [bmi=" + bmi + ", height=" + height
+ ", competition=" + competition + ", name=" + name
+ ", address=" + address + ", dob=" + dob + ", mempaid="
+ mempaid + "]";
}
public void setCompetition(ArrayList<Competition> competition) {
this.competition = competition;`enter code here`
}
}
ArrayList has a method which can remove by Object:
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob");
arr.remove("Bob");
it removes the first instance of the object.
You could of course simulate the same debavior:
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob");
String searchTerm = "Bob";
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).equals(searchTerm) {
arr.remove(i);
break;
}
}
This deviation from the built in method would only be recommended if you wanted to have the search delete on some other, or similar condition. For example if it contained the word "Bob"...
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob Bobingston");
String searchTerm = "Bob";
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).contains(searchTerm)) {
arr.remove(i);
break;
}
}
It seems as if you already have a loop set-up for it. Just loop through the members, check if the name equals what you're looking for, then remove that member from the list if it is
for(Member mem : players) { //loop through each member in list
if(mem.getName().equalsIgnoreCase("name")) { //check if member's name is "name"
players.remove(mem); //removes member from list if it is
}
}
equalsIgnoreCase(String) checks the string without checking for case sensitivity. It won't care for capitalization. If you care about capitalization, use equals(String)

Using polymorphism to display output of a arraylist

I need to display the first and last names of all contact entered when user selected Display contacts from the menu. I also need to display all details of the contacts when the user inputs the Contact ID entered into the ArrayList.
All I can get to display is the last contact entered. Am I not keeping the ArrayList once I go through once then go back to the menu and enter another contact? Or am I just not calling the print function right still to print all contacts in the arraylist.
If I enter 3 now it just goes back to the first line of the array and wants me to enter a contact ID, and goes through creating a contact again, not displaying what is already there.
package ooo1;
import java.util.ArrayList;
import java.util.Scanner;
public class ContactList {
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
int type = 0;
while(type != 4){
System.out.println("Please select an option:");
System.out.println("Personal Contact: Enter 1");
System.out.println("Business Contact: Enter 2");
System.out.println("Display Contacts List: Enter 3");
System.out.println("4 to quit");
type = input1.nextInt();
if(type == 4){
System.out.println("Goodbye");
break;
}
ArrayList<Contact> contacts = new ArrayList<Contact>();
Scanner input = new Scanner(System.in);
System.out.println("Please enter ContactId : ");
String contactId = input.nextLine();
System.out.println("Please enter First Name : ");
String firstName = input.nextLine();
System.out.println("Please enter Last Name : ");
String lastName = input.nextLine();
System.out.println("Please enter Address : ");
String address = input.nextLine();
System.out.println("Please enter Phone Number : ");
String phoneNumber = input.nextLine();
System.out.println("Please enter Email Address : ");
String emailAddress = input.nextLine();
if(type == 1){
System.out.println("Please enter Birthday: ");
String dateofBirth = input.nextLine();
Contact pcontact = new PersonalContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, dateofBirth);
contacts.add(pcontact);
for (Contact showcontact: contacts){
System.out.println(showcontact.displayContact());
}
}
else if(type == 2){
System.out.println("Please enter Job Title: ");
String jobTitle = input.nextLine();
System.out.println("Please enter Organization: ");
String organization = input.nextLine();
Contact bcontact = new BusinessContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, jobTitle, organization);
contacts.add(bcontact);
for (Contact showcontact: contacts){
System.out.println(showcontact.displayContact());
}
}
else if(type ==3){
for (Contact listcontacts: contacts){
System.out.println(listcontacts.displayFullName());
}
}
}
}
}
Parent Class:
package ooo1;
public abstract class Contact {
String contactId;
String firstName;
String lastName;
String address;
String phoneNumber;
String emailAddress;
public Contact(String contactId,String firstName,String lastName, String address, String phoneNumber, String emailAddress)
{
this.contactId = contactId;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phoneNumber = phoneNumber;
this.emailAddress = emailAddress;
}
public void setContactId(String input){ this.contactId = input; }
public String getContactId(){ return this.contactId; }
public void setFirstName(String input){ this.firstName = input; }
public String getFirstName(){ return this.firstName; }
public void setLastName(String input){ this.lastName = input; }
public String getLastName(){ return this.lastName; }
public void setAddress(String input){ this.address = input; }
public String getAddress(){ return this.address; }
public void setPhoneNumber(String input){ this.phoneNumber = input; }
public String getPhoneNumber(){ return this.phoneNumber; }
public void setEmailAddress(String input){ this.emailAddress = input; }
public String getEmailAddress(){ return this.emailAddress; }
public String displayFullName(){
System.out.println("Contact List:");
return ("First Name:" + this.getFirstName() + "Last Name:" + this.getLastName());
}
public String displayContact(){
return ("ContactID:" + this.getContactId() + "First Name:" + this.getFirstName() + "Last Name:" + this.getLastName() + "Address:" + this.getAddress() + "Phone Number:" + this.getPhoneNumber() + "Email Address" + this.getEmailAddress());
}
}
One of the subclasses: Other same just adds more variables:
package ooo1;
public class PersonalContact extends Contact {
private String dateofBirth;
public PersonalContact(String contactId, String firstName, String lastName, String address, String phoneNumber, String emailAddress, String dateofBirth){
super(contactId, firstName, lastName, address, phoneNumber, emailAddress);
this.dateofBirth = dateofBirth;
}
public void setDateofBirth(String input){ this.dateofBirth=input; }
public String getDateofBirth(){ return this.dateofBirth; }
#Override
public String displayContact(){
System.out.println("Personal Contacts:");
return super.displayContact() + "Date of Birth: " + this.getDateofBirth();
}
}
So here is a small example on how to use polymorphism, it's basically your classes stripped down to a bar minimum (this is what the SSCCE is about - stripping what's not relevant, like comments and multiple attributes that behaves the same etcetera).
When you call the displayContact() method in the on the Contact objects stored in the ArrayList polymorphism makes sure the correct displayContact method is used.
The reason PersonalContact.displayContacts(); won't work is that you need to call the method on on object as it's not a static method.
I hope this example helps:
// Contact.java
public abstract class Contact {
private final String name;
public Contact(String name) {
this.name = name;
}
public String displayContact() {
return "Contact name: "
+ name + ". Contact type: "
+ this.getClass().getName() + ". ";
}
}
// PersonalContact.java
public class PersonalContact extends Contact {
private final String dateofBirth;
public PersonalContact(String name, String dateOfBirth) {
super(name);
this.dateofBirth = dateOfBirth;
}
#Override
public String displayContact() {
return super.displayContact() + "Date of birth: " + dateofBirth + ".";
}
}
// BusinessContact.java
public class BusinessContact extends Contact {
private final String organization;
public BusinessContact(String name, String org) {
super(name);
this.organization = org;
}
#Override
public String displayContact() {
return super.displayContact() + "Organization: " + organization + ".";
}
}
// ContactList.java
import java.util.ArrayList;
public class ContactList {
public static void main(String[] args) {
ArrayList<Contact> contacts = new ArrayList<>();
PersonalContact personalContact1 = new PersonalContact("John", "1980-01-01");
BusinessContact businessContact1 = new BusinessContact("theCompany", "The Company");
contacts.add(personalContact1);
contacts.add(businessContact1);
for (Contact contact : contacts) {
System.out.println(contact.displayContact());
}
}
}
EDIT added some more referencing issues mentioned in a comment.
The reason you can't print out anything is that the block of code asking for input is always executed as it's not contained in the type 1 or 2 blocks. To remedy that I'd suggest the following changes:
First, move the ArrayList and Scanner to the start of the main method:
ArrayList<Contact> contacts = new ArrayList<Contact>();
Scanner input = new Scanner(System.in);
Then enclose the entire block of code dealing with input in an if block so it looks like this:
if(type==1 || type==2){
Contact contact = null;
System.out.println("Please enter ContactId : ");
String contactId = input.nextLine();
System.out.println("Please enter First Name : ");
String firstName = input.nextLine();
System.out.println("Please enter Last Name : ");
String lastName = input.nextLine();
System.out.println("Please enter Address : ");
String address = input.nextLine();
System.out.println("Please enter Phone Number : ");
String phoneNumber = input.nextLine();
System.out.println("Please enter Email Address : ");
String emailAddress = input.nextLine();
if(type == 1){
System.out.println("Please enter Birthday: ");
String dateofBirth = input.nextLine();
contact = new PersonalContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, dateofBirth);
}
else if(type == 2){
System.out.println("Please enter Job Title: ");
String jobTitle = input.nextLine();
System.out.println("Please enter Organization: ");
String organization = input.nextLine();
contact = new BusinessContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, jobTitle, organization);
}
// add the new contact
contacts.add(contact);
// print out the newly created contact here
System.out.println(contact.displayContact());
}
Also, you don't really need two Scanner-objects, just reuse one of them :)
And you should consider moving the if(type==4) to after the other blocks so that it comes in order (that's just a matter of style though).

Creating a contact list with java and object oriented

I am new to programming and object oriented design. This is my last requirement to finish my bachelors degree (not in programming). I am so confused with how to make object oriented work, and nothing I look at seems to help.
The assignment is to create a contact list that uses inheritance, polymorphism,and collections. I need a contact list that is stores two types of contacts: business and personal.
1. Prompt to select which contact to add or display.
2. Prompt to allow user to enter the contact info.
3. Prompt that will display the output of a chosen contact back.
I have the following class and subclasses. I am stuck on how I am supposed to read in the inputs to the specific arraylists. I don't even know if the classes are built right either.
Any help would be awesome, I just need to get through this, then I will gladly leave programing to those that know what they are doing.
This is what I have for my Parent Class:
package ooo1;
public abstract class Contact {
private String contactId;
private String firstName;
private String lastName;
private String address;
private String phoneNumber;
private String emailAddress;
public Contact(String contactId,String firstName,String lastName, String address, String phoneNumber, String emailAddress)
{
this.contactId = contactId;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phoneNumber = phoneNumber;
this.emailAddress = emailAddress;
}
public void setContactId(String input){
this.contactId = input;
}
public String getContactId(){
return contactId;
}
public void setFirstName(String input){
this.firstName = input;
}
public String getFirstName(){
return firstName;
}
public void setLastName(String input){
this.lastName = input;
}
public String getLastName(){
return lastName;
}
public void setAddress(String input){
this.address = input;
}
public String getAddress(){
return address;
}
public void setPhoneNumber(String input){
this.phoneNumber = input;
}
public String getPhoneNumber(){
return phoneNumber;
}
public void setEmailAddress(String input){
this.emailAddress = input;
}
public String getEmailAddress(){
return emailAddress;
}
void displayContact(){
System.out.println("Contact ID:" + contactId + " First Name:" + firstName + " Last Name:" + lastName);
System.out.println("Address:" + address);
System.out.println("Phone Number:" + phoneNumber);
System.out.println("Email Address:" + emailAddress);
}
}
This is one of my subclasses:
package ooo1;
public class PersonalContact extends Contact {
private String dateofBirth;
public PersonalContact(String contactId, String firstName, String lastName, String address, String phoneNumber, String emailAddress, String dateofBirth){
super(contactId, firstName, lastName, address, phoneNumber, emailAddress);
this.dateofBirth = dateofBirth;
}
public void setDateofBirth(String input){
this.dateofBirth=input;
}
public String getDateofBirth(){
return this.dateofBirth;
}
}
This is my other subclass:
package ooo1;
public class BusinessContact extends Contact {
private String jobTitle;
private String organization;
public BusinessContact(String contactId, String firstName, String lastName, String address, String phoneNumber, String emailAddress, String jobTitle, String organization){
super(contactId, firstName, lastName, address, phoneNumber, emailAddress);
this.jobTitle = jobTitle;
this.organization = organization;
}
public void setJobTitle(String input){
this.jobTitle = input;
}
public String getJobTitle(){
return this.jobTitle;
}
public void setOrganization(String input){
this.organization = input;
}
public String getOrganization(){
return this.organization;
}
}
This is what I have for Main which is so wrong at this point I believe:
package ooo1;
import java.util.ArrayList;
import java.util.Scanner;
public class ContactList {
public static void main(String[] args) {
ArrayList<PersonalContact> personalList = new ArrayList<PersonalContact>();
Scanner input = new Scanner(System.in);
System.out.println("Please enter ContactId : ");
String contactId = input.nextLine();
System.out.println("Please enter First Name : ");
String firstName = input.nextLine();
System.out.println("Please enter Last Name : ");
String lastName = input.nextLine();
System.out.println("Please enter Address : ");
String address = input.nextLine();
System.out.println("Please enter Phone Number : ");
String phoneNumber = input.nextLine();
System.out.println("Please enter Email Address : ");
String emailAddress = input.nextLine();
System.out.println("Please enter Birthday: ");
String dateofBirth = input.nextLine();
}
}
You have the pieces in place you just need to put them together. First, think about the List being used. It is supposed to hold both types of contacts, however its type argument is using the derived type PersonalContact. Instead use the base class Contact
List<Contact> contacts = new ArrayList<Contact>();
Next it appears you start to gather the information about the contact from the end user via the console. Before doing this you may want to ask what type of contact is being entered, maybe give the option to enter 1 for a personal contact or 2 for a business contact. Then collect the information specific to the type of contact they chose.
Scanner input = new Scanner(System.in);
System.out.println("Please enter Specify the contact type (1 Personal, 2 Business) : ");
int contactType = input.nextInt();
//collect data common to both types
if(contactType == 1){
//collect information specific to personal
} else if(contactType ==2){
//collect information specific to business
}
Next you need to turn the data you collected into the actual objects, using a the constructors. This will need to be done conditionally and could actually be a part of the last section if done properly.
Contact contact;
if(contactType == 1){
contact = new PersonalContact(/*arguments here*/);
} else{
contact = new BusinessContact(/*arguments here*/);
}
Then finish up by adding the contact to your list:
contacts.add(contact);
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaprac;
/**
*
* #author Arijit
*/
public class Contact {
private String name;
private int number;
public Contact(int number,String name) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
public static Contact createContact(int number, String name){
return new Contact(number,name);
}
}
This is the Contact class, which is governed by a contact name and a contact number. Next we will design the MobilePhone class which will have a number(optional) and an arraylist of contacts.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaprac;
import java.util.ArrayList;
/**
*
* #author Arijit
*/
class MobilePhone1 {
public int mynumber;
public ArrayList < Contact > contacts;
public MobilePhone1(int mynumber) {
this.mynumber = mynumber;
this.contacts = new ArrayList < Contact > ();
}
public Boolean addContact(Contact contact) {
if (findPosition(contact) >= 0) {
System.out.println("Contact already is phone");
return false;
} else {
contacts.add(contact);
}
return true;
}
public ArrayList < Contact > getContacts() {
return contacts;
}
public void updateContact(Contact oldContact, Contact newContact) {
if (findPosition(oldContact) >= 0) {
contacts.set(findPosition(oldContact), newContact);
} else {
System.out.println("Contact does not exist");
}
}
public void removeContact(Contact contact) {
if (findPosition(contact) >= 0) {
contacts.remove(findPosition(contact));
} else {
System.out.println("No contact");
}
}
public int searchContact(Contact contact) {
int position = findPosition(contact);
if (contacts.contains(contact)) {
System.out.println("Item found at position");
return position;
}
System.out.println("Not found");
return -1;
}
private int findPosition(Contact contact) {
return this.contacts.indexOf(contact);
}
private int findPosition(String name) {
for (int i = 0; i < contacts.size(); i++) {
Contact contact = this.contacts.get(i);
if (contact.getName().equals(name)) {
return i;
}
}
return -1;
}
}
public class MobilePhone {
public static void main(String args[]) {
Boolean quit = false;
int choice = 0;
java.util.Scanner sc = new java.util.Scanner(System.in);
MobilePhone1 phone = new MobilePhone1(98312);
//Contact newcontact = Contact.createContact(12345,"Arijt");
while (!quit) {
System.out.println("Enter your choice");
choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 0:
System.out.println("Enter the number of Contacts");
int count = sc.nextInt();
for (int i = 0; i < count; i++) {
System.out.println("Enter number");
int phoneNumber = sc.nextInt();
System.out.println("Enter Name");
sc.nextLine();
String name = sc.nextLine();
Contact newcontact = Contact.createContact(phoneNumber, name);
phone.addContact(newcontact);
}
break;
case 1:
int size = phone.getContacts().size();
System.out.println(size);
for (int i = size - 1; i >= 0; i--) {
phone.removeContact(phone.getContacts().get(i));
}
System.out.println(phone.getContacts().isEmpty());
break;
case 2:
for (int i = 0; i < phone.getContacts().size(); i++) {
System.out.println(phone.searchContact(phone.getContacts().get(i)));
}
break;
case 3:
//Contact newcontact1 = Contact.createContact(12345,"Buzz");
System.out.println("Enter the Contact name you want to update");
String oldContactName = sc.nextLine();
for (int j = 0; j < phone.getContacts().size(); j++) {
if (phone.getContacts().get(j).getName().equals(oldContactName)) {
System.out.println("Enter the new Contact name");
String newName = sc.nextLine();
System.out.println("Enter the new Contact number");
int newNumber = sc.nextInt();
phone.updateContact(phone.getContacts().get(j), Contact.createContact(newNumber, newName));
} else {
System.out.println("You are looking for the wrong contact");
}
}
for (int i = 0; i < phone.getContacts().size(); i++) {
System.out.println(phone.getContacts().get(i).getName() + "," + phone.getContacts().get(i).getNumber());
}
break;
case 4:
if(phone.getContacts().isEmpty()){
System.out.println("Emtpty contact list");
}
else {
System.out.println("Contact list");
for (int i = 0; i < phone.getContacts().size(); i++) {
System.out.println("Name: "+phone.getContacts().get(i).getName() + ",Phone Number: " + phone.getContacts().get(i).getNumber());
}
}
break;
case 6:
System.out.println("Enter 0 for adding contact\n");
System.out.println("Enter 1 for removing every contact\n");
System.out.println("Enter 2 for searching contact\n");
System.out.println("Enter 3 for updating contact\n");
System.out.println("Enter 4 for viewing the contact list\n");
System.out.println("Enter 6 for exiting\n");
System.out.println("Enter 5 to see the instrusctions again\n");
break;
case 5:
quit = true;
break;
}
}
}
}

Categories