Creating a contact list with java and object oriented - java

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;
}
}
}
}

Related

Edit and Update ArrayList in Java

I am trying to update myArray list by allowing the user to change their first and last name while keeping other information in the arraylist the same.
the code follows
public void editStudentID(int findStudentId) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() != findStudentId) {
continue;
}
System.out.println("Found a profile containing information for " + findStudentId + ":");
System.out.println("What would you like to change in your profile?");
System.out.println("1.First Name");
System.out.println("2.Last Name");
int decision = scanner.nextInt();
switch (decision) {
case 1:
System.out.println("Enter a new first name to continue");
String newFirstName = scanner.next();//need to find a way to update this in my arraylist
break;
case 2:
System.out.println("Enter a new last name to continue");
String newLastName = scanner.next();//this as well
break;
}
return;
}
System.out.println(" Id not found ");
}
this is my Student class where I only wrote final for only my id and dob to not be changed by the user
public class Student {
private final int id;
private String firstName;
private String lastName;
private final String dob;
public Student(int id, String firstName, String lastName, String dob) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getDob() {
return dob;
}
public static Student createStudentID(int id, String firstName, String lastName, String dob) {
return new Student(id, firstName, lastName, dob);
}
}
First, you need to make you Student class mutable, but supplying a couple of "setters" which will allow you to change the first and last name properties, for example
public class Student {
//...
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Then in you editStudentID method, you simply update the required record, for example
public void editStudentID(int findStudentId) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() != findStudentId) {
continue;
}
System.out.println("Found a profile containing information for " + findStudentId + ":");
System.out.println("What would you like to change in your profile?");
System.out.println("1.First Name");
System.out.println("2.Last Name");
int decision = scanner.nextInt();
switch (decision) {
case 1:
System.out.println("Enter a new first name to continue");
String newFirstName = scanner.next();//need to find a way to update this in my arraylist
students.get(i).setFirstName(newFirstName);
break;
case 2:
System.out.println("Enter a new last name to continue");
String newLastName = scanner.next();//this as well
students.get(i).setLastName(newFirstName);
break;
}
return;
}
System.out.println(" Id not found ");
}

How to search for an element in an array? and How to add variables with declared methods into an array list?

I have 2 major troubles (that I'm aware of) with this program. Firstly, I don't know how to get FinalGrade and LetterGrade into the array. Secondly, I don't know how to use last name and first name to search for a student in the array. Let me know if you find other problems with my program. Thanks
This is the 1st class
package student;
public class Person {
protected String FirstName, LastName;
//Constructor
public Person(String FirstName, String LastName) {
this.FirstName = FirstName;
this.LastName = LastName;
}
//Getters
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
//Setters
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
}
This is the 2nd class:
package student;
import java.util.ArrayList;
import java.util.Scanner;
public class Student extends Person{
private int HomeworkAve, QuizAve, ProjectAve, TestAve;
private double FinalGrade;
private String LetterGrade;
//Constructor for the averages
public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, String FirstName, String LastName)
{
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;
}
//Method to calculate final grade and letter grade
//Final grade calculation
public double CalcGrade (int HomeworkAve, int QuizAve, int ProjectAve, int TestAve)
{
FinalGrade = (double)(0.15*HomeworkAve + 0.05*QuizAve + 0.4 * ProjectAve + 0.4*TestAve);
return FinalGrade;
}
//Letter grade calculation
public String CalcGrade ( double FinalGrade)
{
if ( FinalGrade >= 90.00)
LetterGrade="A";
else if(FinalGrade >= 80.00)
LetterGrade="B";
else if(FinalGrade>=70.00)
LetterGrade="C";
else if(FinalGrade>=60.00)
LetterGrade="D";
else LetterGrade="F";
return LetterGrade;
}
public String getFullName (String FirstName,String LastName)
{
String str1 = FirstName;
String str2 = LastName;
String FullName = str1+","+str2;
return FullName;
}
public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, double FinalGrade, String LetterGrade, String FirstName, String LastName) {
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;
this.FinalGrade = FinalGrade;
this.LetterGrade = LetterGrade;
}
//Setters for this student class
public void setHomeworkAve(int HomeworkAve) {
this.HomeworkAve = HomeworkAve;
}
public void setQuizAve(int QuizAve) {
this.QuizAve = QuizAve;
}
public void setProjectAve(int ProjectAve) {
this.ProjectAve = ProjectAve;
}
public void setTestAve(int TestAve) {
this.TestAve = TestAve;
}
public void setFinalGrade(int FinalGrade) {
this.FinalGrade = FinalGrade;
}
public void setLetterGrade(String LetterGrade) {
this.LetterGrade = LetterGrade;
}
//Getters for this student class
public int getHomeworkAve() {
return HomeworkAve;
}
public int getQuizAve() {
return QuizAve;
}
public int getProjectAve() {
return ProjectAve;
}
public int getTestAve() {
return TestAve;
}
public double getFinalGrade() {
return FinalGrade;
}
public String getLetterGrade() {
return LetterGrade;
}
public void DisplayGrade (){
System.out.println(FirstName+" "+LastName+"/nFinal Grade: "+FinalGrade+"/nLetter Grade: "+ LetterGrade);
}
public static void main(String[] args){
Scanner oScan = new Scanner(System.in);
Scanner iScan = new Scanner(System.in);
boolean bContinue = true;
int iChoice;
ArrayList<Student> students = new ArrayList<>();
while (bContinue == true)
{
//The menu
System.out.println("1. New Class List");
System.out.println("2. Search for a Student");
System.out.println("3. Exit");
System.out.println("Choose an item");
iChoice = iScan.nextInt();
//The 1st case: when the user wants to enter the new list
if (iChoice == 1){
System.out.println("Enter the number of students");
int numberOfStudents = iScan.nextInt();
for(int iCount = 0;iCount < numberOfStudents;){
System.out.println("Enter the name for Student " + ++iCount);
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();
System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();
System.out.println("Enter Homework Average");
int HomeworkAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Quiz Average");
int QuizAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Project Average");
int ProjectAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Test Average");
int TestAve = iScan.nextInt();
System.out.println();
How to get FinalGrade and LetterGrade??
Student hobbit = new Student(HomeworkAve,QuizAve, ProjectAve,TestAve,FirstName, LastName);
students.add(hobbit);
}
}
//The 2nd case: when the user wants to search for a student
else if (iChoice == 2)
{
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();
System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();
Here is my revised code to find the student but I don't know how to print the array after I found it
int i = 0;
for (Student student : students) {
if (FirstName != null & LastName != null);{
if (student.getFirstName().equals(FirstName) && student.getLastName().equals(LastName)) {
System.out.println(students.get(i)); //this doesn't work
break;
}
i++;
}
}
//The 3r case: when the user wants to exit
else if (iChoice == 3)
{
bContinue = false;
}
}
}
}
You have an ArrayList of type Student and you are doing indexOf on a variable of type String. You will have to traverse the entire ArrayList and then do a comparison to find out if the student name mathces. Sample code:
int i = 0;
for (Student student : students) {
// Add null checks if first/last name can be null
if (student.getFirstName().equals(firstName) && student.getLastName().equals(lastName)) {
System.out.println("Found student at " + i);
break;
}
i++;
}
FinalGrade and LetterGrade are variables in each object, I think you are mistaken about the concept of an Array/ArrayList. The ArrayList only holds each Student object, not the variable in each object. You can go through each student and get their finalGrade and letterGrade with the get* functions. Before doing this, you should make a call to CalcGrade methods so the grades are calculated.

Java JOptionPane.showInputDialog with constructor

First post, I hope I don't seem to n00bish.
I am in a Java class and am stuck with a problem.
The requirement is to make a class (Contact) which has getters and a constructor for name, email and phoneNumber. Then a test class (TestContact) which has a while loop that keeps prompting the user because the hit OK and didn't type anything, hit Enter or the name is over 21 characters.
Also, the three variables I need (name, email and phone number) are to be entered in the same input box (parsed by the whitespace between).
I can't seem to figure out how to get it working. I have many bugs.
Firstly, I'm not sure how I can setup the array and then split it with the whitespace then use that array to set my variable & getters (hope that makes sense?).
Also, the program keeps crashing because of NullPointerException in the array and array index out of bounds exception.
Contact class:
public class Contact
{
//Initiating variables
private String name;
private String phoneNumber;
private String eMail;
//Constructor
public Contact()
{
this.name = getName();
this.phoneNumber = getPhoneNumber();
this.eMail = getEMail();
}
//Getter for name variable
public String getName()
{
return name;
}
//Getter for phoneNumber variable
public String getPhoneNumber()
{
return phoneNumber;
}
//Getter for eMail variable
public String getEMail()
{
return eMail;
}
}
TestContact class:
public class testContact
{
public static void main(String[] args)
{
Contact myContact = new Contact();
String userInput;
String noUserInput;
userInput = JOptionPane.showInputDialog("Please enter your First and Last Name, Phone Number, & E-mail: ");
do
{
String[] phrases = userInput.split(" ");
String name = phrases[0] + " " + phrases[1];
String phoneNumber = phrases[2];
String eMail = phrases[3];
if (!userInput.equals(""))
{
if (name.length() > 21)
{
String userInput = JOptionPane.showInputDialog("I'm sorry but your name is too long.\nPlease enter your First and Last Name, Phone Number, & E-mail: ");
String[] phrases = userInput.split(" ");
String name = phrases[0] + " " + phrases[1];
String phoneNumber = phrases[2];
String eMail = phrases[3];
JOptionPane.showMessageDialog(null, "Name: "+myContact.getName()+"\nPhone Number: "+myContact.getPhoneNumber()+"\nE-Mail: "+myContact.getEMail());
}
else
{
JOptionPane.showMessageDialog(null, "Name: "+name+"\nPhone Number: "+phoneNumber+"\nE-Mail: "+eMail);
}
}
while ((userInput = JOptionPane.showInputDialog("I'm sorry but you didn't enter anything.\nPlease enter your First and Last Name, Phone Number, & E-mail: ")) == null)
{
String[] phrases = userInput.split(" ");
String name = phrases[0] + " " + phrases[1];
String phone = phrases[2];
String eMail = phrases[3];
JOptionPane.showMessageDialog(null, "Name: "+myContact.getName()+"\nPhone Number: "+myContact.getPhoneNumber()+"\nE-Mail: "+myContact.getEMail());
}
}while(userInput != null);
}
}
NOTE
I changed around my TestContact class to make it a bit nicer see below. My only issue is how to set the method with what I parsed from the string array and put into string variables. How would I set those for the constructor??
public class testContact
{
static String userInput;
static Contact myContact = new Contact();
public static void main(String[] args)
{
do
{
parsing(initialInput());
if (!userInput.equals(""))
{
if (myContact.getName().length() > 21)
{
parsing(nameLengthErrorInput());
output();
}
else
{
output();
}
}
else
{
parsing(nullErrorInput());
output();
}
}while(userInput != null);
}
public static String initialInput()
{
userInput = JOptionPane.showInputDialog("Please enter your First and Last Name, Phone Number, & E-mail: ");
return userInput;
}
public static String nameLengthErrorInput()
{
userInput = JOptionPane.showInputDialog("I'm sorry but your name is too long.\nPlease enter your First and Last Name, Phone Number, & E-mail: ");
return userInput;
}
public static String nullErrorInput()
{
userInput = JOptionPane.showInputDialog("I'm sorry but you didn't enter anything.\nPlease enter your First and Last Name, Phone Number, & E-mail: ");
return userInput;
}
public static void output()
{
JOptionPane.showMessageDialog(null, "Name: "+myContact.getName()+"\nPhone Number: "+myContact.getPhoneNumber()+"\nE-Mail: "+myContact.getEMail());
}
public static void parsing(String userInput)
{
String[] phrases = userInput.split(" ");
String name = phrases[0] + " " + phrases[1];
String phoneNumber = phrases[2];
String eMail = phrases[3];
}
}
My issue is now sole in the parsing() method.
There are two primary errors...
First...
In the Contact constructor, you assigning the variables back to themselves...
public Contact() {
this.name = getName();
this.phoneNumber = getPhoneNumber();
this.eMail = getEMail();
}
This is pretty much the same as saying...
public Contact() {
this.name = this.name;
this.phoneNumber = this.phoneNumber;
this.eMail = this.eMail;
}
The result is the same...
Second...
You're getting a NullPointerException here...
if (myContact.getName().length() > 21) {
Because the value of Contact#getName has never been assigned (a valid) value
Suggestions...
First...
I would suggest changing the Contact constructor to require values to passed to it...
public Contact(String name, String phoneNumber, String eMail) {
this.name = name;
this.phoneNumber = phoneNumber;
this.eMail = eMail;
}
This will mean that...
static Contact myContact = new Contact();
Will no longer compile, but you can change it to
static Contact myContact;
instead...
Second...
I would suggest changing your parsing method to return a Contact, for example...
public static Contact parsing(String userInput) {
Contact contact = null;
if (userInput != null && userInput.trim().length() > 0) {
String[] phrases = userInput.split(" ");
if (phrases.length == 4) {
String name = phrases[0] + " " + phrases[1];
String phoneNumber = phrases[2];
String eMail = phrases[3];
contact = new Contact(name, phoneNumber, eMail);
}
}
return contact;
}
You should also be guarding against invalid input as well.
This means you would need to assign the result each time you use one of your parsing methods...
myContact = parsing(initialInput());
Third...
Each time a user fails to enter what you need, you should simply display an error message and make enter new information, you're kind of trying to do that, but you're not taking advantage of your existing error checking to re-validate the input...
public static void main(String[] args) {
String errorMsg = "";
do {
myContact = parsing(getInput(errorMsg));
if (myContact != null) {
if (myContact.getName().length() > 21) {
myContact = null;
errorMsg = "<html>I'm sorry but your name is too long.<br>";
}
} else {
errorMsg = "<html>I'm sorry but you didn't enter anything.<br>";
}
} while (myContact == null);
output();
}
public static String getInput(String errorMsg) {
userInput = JOptionPane.showInputDialog(errorMsg + "Please enter your First and Last Name, Phone Number, & E-mail: ");
return userInput;
}
So I just submitted my lab and this is my final solution
Contact class:
public class Contact
{
private String name;
private String phoneNumber;
private String eMail;
public Contact(String name, String phoneNumber, String eMail)
{
this.name = name;
this.phoneNumber = phoneNumber;
this.eMail = eMail;
}
public String getName()
{
return name;
}
public String getPhoneNumber()
{
return phoneNumber;
}
public String getEMail()
{
return eMail;
}
}
TestContact class:
import javax.swing.JOptionPane;
public class testContact
{
static Contact myContact;
static Boolean exitBool = true;
public static void main(String[] args)
{
myContact = parsing(initialInput());
do
{
if (myContact != null)
{
if (myContact.getName().length() > 21)
{
myContact = parsing(nameLengthErrorInput());
exitBool = false;
}
else
{
exitBool = true;
}
}
else if (myContact == null)
{
myContact = parsing(nullErrorInput());
exitBool = false;
//output();
}
}while(exitBool == false);
output();
}
public static String initialInput()
{
userInput = JOptionPane.showInputDialog("Please enter your First and Last Name, Phone Number, & E-mail: ");
return userInput;
}
public static String nameLengthErrorInput()
{
userInput = JOptionPane.showInputDialog("I'm sorry but your name is too long.\nPlease enter your First and Last Name, Phone Number, & E-mail: ");
return userInput;
}
public static String nullErrorInput()
{
userInput = JOptionPane.showInputDialog("I'm sorry but you didn't enter anything.\nPlease enter your First and Last Name, Phone Number, & E-mail: ");
return userInput;
}
public static void output()
{
JOptionPane.showMessageDialog(null, "Name: "+myContact.getName()+"\nPhone Number: "+myContact.getPhoneNumber()+"\nE-Mail: "+myContact.getEMail());
}
public static Contact parsing(String userInput) {
Contact contact = null;
if (userInput != null && userInput.trim().length() > 0) {
String[] phrases = userInput.split(" ");
String name = phrases[0] + " " + phrases[1];
String phoneNumber = phrases[2];
String eMail = phrases[3];
contact = new Contact(name, phoneNumber, eMail);
}
return contact;
}
}

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).

Insert array list in parent class to override with subclasses

I am new to OOP and programming in general. I am having trouble with how to put things in the parent class and call them from the other classes and main.
I have the following arraylist creators in main, but feel to be really OOP these should be in the parent and subclasses and just called from main. Is this is correct can someone help me with how this would work.
How do I get the arraylist in the parent class and then call it correctly from main?
This is what I have for main:
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 != 5){
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 Personal Contacts: Enter 3");
System.out.println("Display Business Contacts: Enter 4");
System.out.println("5 to quit");
type = input1.nextInt();
if(type == 5){
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);
}
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);
}
}
}
}
This is what I have for the parent class:
package ooo1;
import java.util.ArrayList;
import java.util.Scanner;
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 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 displayContacts(){
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);
}
}
One of my subclasses: other same just adds a few more variables:
Display Contact(): doesn't work not sure what to do with it either.
/*
* 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 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 void displayContacts(){
System.out.print("Personal Contacts: ");
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);
System.out.println("Birthday:" + dateofBirth);
}
}
You probably want something like this.
public class AddressBook<T extends Contact>
{
private List<T> contacts = new ArrayList<T>();
public void addContact(T contact)
{
contacts.add(contact);
}
}
You could instantiate and use this class like this.
AddressBook<Contact> book = new AddressBook<Contact>();
book.add(new PersonalContact(...));
book.add(new BusinessContact(...));
Then over time you have the flexibility to add methods to AddressBook that work with the underlying collection. For instance you might want to search for contacts with a particular name. Or return an iterator of Contacts ordered by a particular attribute.
You can add a method in class Contact :
public void getData(){
// take in all the inputs here, so that you can directly store them in class member variables instead of passing them from main.
}
Assuming that PersonalContact & BusinessContact are inherited classes from Contact.
You can add a method in them:
class PersonalContact extends Contact{
String dateofBirth;
public void getData(){
super.getData(); //calls getData() method from base class
// take DOB as input & store it
}
similarly for BusinessContact class.
I suggest you take a look at abstract classes & interfaces for future use.
The Contact class seems okay. But ContactList not that much. It's supposed to be a data structure for contacts, so there's not reason for main method there.
public class ContactList {
private ArrayList<Contact> contacts;
public ContactList(){
this.contacts = new ArrayList<Contact>();
}
public void addContact(Contact contact){
this.contacts.add(contact);
}
public Contact getContact(int index){
return contacts.get(index);
}
// other methods that work with the data structure
// f.e. searching, deleting, ...
}
and then you could have some ContactUtil class that would take care of reading contact info from user (what you had in you main method).
public final class ContactUtil {
private ContactUtil(){} // we don't want to create instances of this class
public static Contact readNewContact(){
Scanner input1 = new Scanner(System.in);
int type = 0;
...
return contact;
}
}
And finally you will have some class just for main():
public class Main {
public static void main(String[] args){
ContactList myContacs = new ContactList();
myContacts.add(ContactUtil.readNewContact());
Contact contact = ContactUtil.readNewContact();
myContacts.add(contact);
}
}

Categories