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;
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
Running into trouble with the output of my code (listed below, separate files and all) where I can execute the correct action up until I need to execute one directly after another. It's spitting out the Exception in thread "main" java.lang.NullPointerException error along with at which lines it is incorrect, however I don't know how to fix it as of now. (This is done in Eclipse compiler)
public class Assignment4
{
public static void main (String[] args)
{
// local variables, can be accessed anywhere from the main method
char input1 = 'Z';
//String inputInfo= "";
String name, firstName, lastName, city ;
int years = 0;
String line = new String();
// instantiate a Team object
Team suns = null;
printMenu();
//Create a Scanner object to read user input
Scanner scan = new Scanner(System.in);
do // will ask for user input
{
System.out.println("What action would you like to perform?");
line = scan.nextLine();
if (line.length() == 1)
{
input1 = line.charAt(0);
input1 = Character.toUpperCase(input1);
// matches one of the case statement
switch (input1)
{
case 'A': //Add a coach
System.out.print("Please enter the Coach's information:\n");
System.out.print("Enter coach's first name:\t");
firstName = scan.nextLine();
System.out.print("Enter coach's last name:\t");
lastName = scan.nextLine();
System.out.print("Enter coach's years of experience:\t");
years = scan.nextInt();
scan.nextLine();
Coach sunsCoach = new Coach(firstName, lastName, years);
System.out.print("\nPlease enter the Team's information:");
System.out.print("\nEnter teams name:\t");
name = scan.nextLine();
System.out.print("Enter Team's city:\t");
city = scan.nextLine();
suns = new Team(name, sunsCoach, city);
break;
case 'D': //Display course
System.out.print(suns.toString());
break;
case 'Q': //Quit
break;
case '?': //Display Menu
printMenu();
break;
default:
System.out.print("Unknown action\n");
break;
}
}
else
{
System.out.print("Unknown action\n");
}
} while (input1 != 'Q' || line.length() != 1);
scan.close();
}
/** The method printMenu displays the menu to a user **/
public static void printMenu()
{
System.out.print("Choice\t\tAction\n" +
"------\t\t------\n" +
"A\t\tAdd Coach\n" +
"D\t\tDisplay Team\n" +
"Q\t\tQuit\n" +
"?\t\tDisplay Help\n\n");
}
}
Along with this code, there are my two child class files, Coach.java and Team.java respectively, listed below.
public class Coach
{ String firstName, lastName; //constructor
int years;
{ String numYears;
firstName = lastName = numYears = "?";
}
public Coach(String first, String last, int years) { //Set variables
firstName = first;
lastName = last;
int numYears = years;
}
//Accessors
public String getFirstName()
{return firstName;}
public String getLastName()
{return lastName;}
public String getYears()
{String numYears = null;
return numYears;}
// Mutators
public void setFirstName(String theFirstName)
{firstName = theFirstName;}
public void setLastName(String theLastName)
{lastName = theLastName;}
public void setYears(int years)
{int numYears = years;}
public String toString() {
String output = "\nLast Name:\t" + lastName + "\nFirst Name:\t " + firstName;
output += "\nYears of Experience:\t " + getYears() + "\n";
return output;
}
}
public class Team {
String teamName;
Coach coach;
String getCity;
//Constructor
public Team() {
teamName = getCity = "?";
}
public Team(String name, Coach coach, String cityName)
{ teamName = name;
}
//Accessors
public String getName() {return teamName;}
public Coach getCoach() {return coach;}
public String getCity() {return getCity;}
//Mutators
public void setName(String theName) {teamName = theName;}
public void setCity(String someCity) {getCity = someCity;}
public void setCoach(String firstName, String lastName, int years)
{ coach = new Coach (firstName, lastName, years);
}
public String toString()
{ String output = "Team's name:\t" + teamName + " at " + getCity() + "\nCoach Information:";
output += coach.toString();
return output;
}
}
Running the code, and putting in inputs until I wish to select option D, will eventually yield this specific error:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Coach.toString()" because "this.coach" is null
at Team.toString(Team.java:30)
at Assignment4.main(Assignment4.java:68)
suns = new Team(name, sunsCoach, city);
As I can see you are passing sunsCoach as a parameter to the constructor of Team, but you are not initialising the coach object.
Update your code from
public Team(String name, Coach coach, String cityName)
{
teamName = name;
}
to
public Team(String name, Coach coach, String cityName)
{
teamName = name;
coach = coach;
getCity = cityName;
}
this would resolve the NullPointerException
This assignment requires me to take in input and print it out. The first half of the output is printing currently, but the other half is giving me null. What's wrong here?
Heres my code:
This is the main class.
import java.util.*;
public class Assignment4 {
public static void main(String[] args) {
// local variables, can be accessed anywhere from the main method
char input1 = 'Z';
// String inputInfo= "";
String courseName, firstName, lastName, office, university;
String line = new String();
// instantiate a Course object
Course cse110 = null;
printMenu();
// Create a Scanner object to read user input
Scanner scan = new Scanner(System.in);
do // will ask for user input
{
System.out.println("What action would you like to perform?");
line = scan.nextLine();
if (line.length() == 1) {
input1 = line.charAt(0);
input1 = Character.toUpperCase(input1);
// matches one of the case statement
switch (input1) {
case 'A': // Add a course
System.out.print("Please enter the Instructor information:\n");
System.out.print("Enter instructor's first name:\t");
firstName = scan.nextLine();
System.out.print("Enter instructor's last name:\t");
lastName = scan.nextLine();
System.out.print("Enter instructor's office number:\t");
office = scan.nextLine();
Instructor myInstructor = new Instructor(firstName, lastName, office);
System.out.print("\nPlease enter the Course information:");
System.out.print("\nEnter course name:\t");
courseName = scan.nextLine();
System.out.print("Enter university name:\t");
university = scan.nextLine();
cse110 = new Course(courseName, myInstructor, university);
break;
case 'D': // Display course
System.out.print(cse110.toString());
break;
case 'Q': // Quit
break;
case '?': // Display Menu
printMenu();
break;
default:
System.out.print("Unknown action\n");
break;
}
} else {
System.out.print("Unknown action\n");
}
} while (input1 != 'Q' || line.length() != 1);
scan.close();
}
/** The method printMenu displays the menu to a user **/
public static void printMenu() {
System.out.print("Choice\t\tAction\n" + "------\t\t------\n" + "A\t\tAdd Course\n" + "D\t\tDisplay Course\n"
+ "Q\t\tQuit\n" + "?\t\tDisplay Help\n\n");
}
}
Heres the Course class:
import java.util.*;
public class Course
{
//----------------------------------------------------------------------
// ATTRIBUTES
private String courseName;
private Instructor instructor;
private String university;
//----------------------------------------------------------------------
// CONSTRUCTOR
public Course()
{
courseName = "?";
university = "?";
instructor = null;
}
public Course(String name, Instructor inst, String univer)
{
this.setName(name);
this.setInstructor(name, Instructor.lastName, Instructor.officeNum);
this.setUniversity(univer);
}
//----------------------------------------------------------------------
// ACCESSORS
public String getName()
{
return courseName;
}
public String getUniversity()
{
return university;
}
public Instructor getInstructor()
{
return instructor;
}
//----------------------------------------------------------------------
//METHODS
public void setName(String someName)
{
this.courseName = someName;
}
public void setUniversity(String someUniversity)
{
this.university = someUniversity;
}
public void setInstructor(String firstName, String lastName, String office)
{
Instructor.firstName = firstName;
Instructor.lastName = lastName;
Instructor.officeNum = office;
}
public String toString()
{
return "Course name:\t" + courseName + " at " + university + "\nInstructor Information:" + instructor + "\n";
}
}
Heres the Instructor class:
import java.util.*;
public class Instructor
{
//----------------------------------------------------------------------
// ATTRIBUTES
public static String firstName;
public static String lastName;
public static String officeNum;
//----------------------------------------------------------------------
// CONSTRUCTOR
public Instructor()
{
firstName = "?";
lastName = "?";
officeNum = "?";
}
public Instructor(String first, String last, String office)
{
this.setFirstName(first);
this.setLastName(last);
this.setOfficeNum(office);
}
public Instructor(Instructor inst)
{
firstName = inst.firstName;
lastName = inst.lastName;
officeNum = inst.officeNum;
}
//----------------------------------------------------------------------
// ACCESSORS
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getOfficeNum()
{
return officeNum;
}
//----------------------------------------------------------------------
//METHODS
public void setFirstName(String someFirstName)
{
this.firstName = someFirstName;
}
public void setLastName(String someLastName)
{
this.lastName = someLastName;
}
public void setOfficeNum(String someOffice)
{
this.officeNum = someOffice;
}
public String toString()
{
return ("\nLast Name:\t" + lastName +
"\nFirst Name:\t " + firstName +
"\nOffice Number:\t" + officeNum);
}
}
And finally heres the output:
> Choice Action
------ ------
A Add Course
D Display Course
Q Quit
? Display Help
What action would you like to perform?
A
Please enter the Instructor information:
Enter instructor's first name: John
Enter instructor's last name: Appleseed
Enter instructor's office number: 501
Please enter the Course information:
Enter course name: Intro to Java
Enter university name: ASU
What action would you like to perform?
D
Course name: Intro to Java at ASU
Instructor Information:null
What action would you like to perform?
Instead of Information:null, it should be printing out:
Last name: Appleseed
First name: John
Office Number: 501
How can I fix this?
Thanks!
You've never set the instructor property inside Course, after it is initialized as null. You should not use static fields in Instructor. You should create a new Instructor() and assign the instructor instance to the instructor property of Course
First fix your Instructor class:
public class Instructor
{
/******These should not be public static********/
private String firstName;
private String lastName;
private String officeNum;
...
}
Next fix your Course class
public class Course
{
private String courseName;
private Instructor instructor;
private String university;
public Course(String name, Instructor inst, String univer)
{
this.setName(name);
this.setInstructor(inst);
this.setUniversity(univer);
}
public void setInstructor(Instructor inst)
{
this.instructor = inst;
}
...
}
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).
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);
}
}
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;
}
}
}
}