i dont know how to add an update firstName function with my code. i am fairly new.
public class Contact {
private final String contactID;
private String firstName;
private String lastName;
private String Number;
private String Address;
private static AtomicLong idGenerator = new AtomicLong();
//CONSTRUCTOR
/*
* The constructor takes first name, last name, phone number, and address as parameters.
* The first thing it does is generates a new ID for the contactID field.
*
* First name and last name are checked for null condition or blank fields. If either of
* those conditions exist, fill in the field with the phrase "NULL" so that something exists
* to protect data integrity while making it clear it is a placeholder.
* In both cases, if the first or last name is greater than 10 characters, truncate it
* so that only the first 10 characters are used.
*
* For the number field, if the phone number is not exactly 10 characters then fill it with
* the placeholder '5555555555'.
*
* Address is like first and last names. If it is blank or null, set it to "NULL".
* If it is more than 30 characters, truncate to the first 30 characters.
*/
public Contact(String firstName, String lastName, String number, String address) {
//CONTACTID
//Contact ID is generated when the constructor is called. It is set as a final variable and has
//no other getter or setter so there should be no way to change it.
//The idGenerator is static to prevent duplicates across all contacts.
this.contactID = String.valueOf(idGenerator.getAndIncrement());
//FIRSTNAME
if (firstName == null || firstName.isBlank()) {
this.firstName = "NULL";
//If first name is longer than 10 characters, just grab the first 10 characters
} else if(firstName.length() > 10) {
this.firstName = firstName.substring(0, 10);
} else {
this.firstName = firstName;
}
//LASTNAME
if (lastName == null || lastName.isBlank()) {
this.lastName = "NULL";
} else if(lastName.length() > 10) {
this.lastName = lastName.substring(0,10);
} else {
this.lastName = lastName;
}
//NUMBER
if (number == null || number.isBlank() || number.length() != 10) {
this.Number = "5555555555";
} else {
this.Number = number;
}
//ADDRESS
if (address == null || address.isBlank()) {
this.Address = "NULL";
} else if(address.length() > 30) {
this.Address = address.substring(0,30);
} else {
this.Address = address;
}
}
//GETTERS
public String getContactID() {
return contactID;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getNumber() {
return Number;
}
public String getAddress() {
return Address;
}
}
package ContactService;
import java.util.ArrayList;
public class ContactService {
//Start with an ArrayList of contacts to hold the list of contacts
ArrayList<Contact> contactList = new ArrayList<Contact>();
//Display the full list of contacts to the console for error checking.
public void displayContactList() {
for(int counter = 0; counter < contactList.size(); counter++) {
System.out.println("\t Contact ID: " + contactList.get(counter).getContactID());
System.out.println("\t First Name: " + contactList.get(counter).getFirstName());
System.out.println("\t Last Name: " + contactList.get(counter).getLastName());
System.out.println("\t Phone Number: " + contactList.get(counter).getNumber());
System.out.println("\t Address: " + contactList.get(counter).getAddress() + "\n");
}
}
//Adds a new contact using the Contact constructor, then assign the new contact to the list.
public void addContact(String firstName, String lastName, String number, String address) {
// Create the new contact
Contact contact = new Contact(firstName, lastName, number, address);
contactList.add(contact);
}
public void removeContact (String firstName, String lastName, String number, String address) {
Contact contact = new Contact (firstName, lastName, number, address);
contactList.remove(contact);
}
public void updateFirstName {
}
}
how do i get the updateFirstName function to work. i need to be able to update the first name within a contact, but i dont know if i need to create a new contact like what was done in the add and remove contact functions. ive tried contact.setfirstname = new firstName but that did not work and i am at a loss on what to do.
Related
I'm trying to create a contact service to add/modify/delete contacts and I'm stuck on how to modify a contact. This is the Contact class that I'm starting with:
public class Contact {
private String contactId;
private String firstName;
private String phone;
public Contact (String contactId, String firstName, String phone) {
if (contactId == null || contactId.length() > 10) {
throw new IllegalArgumentException("invalid contact ID");
}
if (firstName == null || firstName.length() > 10) {
throw new IllegalArgumentException("invalid first name");
}
if (phone == null || phone.length() != 10) {
throw new IllegalArgumentException("invalid phone number");
}
this.contactId = contactId;
this.firstName = firstName;
this.phone = phone;
}
public String getContactId() {
return contactId;
}
public String getFirstName() {
return firstName;
}
public String getPhone() {
return phone;
}
}
In my contact service class, I have written the methods for creating and getting a contact
public class ContactService {
int Id = 000;
//create contactList array
private ArrayList<Contact> contactList = new ArrayList<>();
public Contact getContact(String ID) {
//iterates through contact list
Iterator<Contact> itr = contactList.iterator();
while (itr.hasNext()) {
Contact contact = itr.next();
if (contact.getContactId().equals(ID)) {
//returns contact object for matching ID
return contact;
}
}
return null;
}
//adds a contact to the contactList array
public Contact addContact(String firstName, String Phone) {
Id++; //increment ID to make a unique ID
//convert integer to string for ArrayList
String contactId = Integer.toString(Id);
//create contact object
Contact contact = new Contact(contactId, firstName, Phone);
//add contact to list
contactList.add(contact);
return contact;
}
For my updateContact() method, I want to call getContact() which should return a contact object but I'm not sure how to update the object from there. This is probably this closest I've come:
public void updateContact(String contactId, String firstName, String phone) {
getContact(contactId);
contact.setFirstName(firstName);
contact.setPhone(phone);
}
However, not only does this approach not work but it would require me to create setter methods. If I do that the new input does not go through the null and length checks contained in the Contact constructor.
Your update method does not work because you are calling getContact without storing return value of the method
public void updateContact(String contactId, String firstName, String phone) {
Contact contact = getContact(contactId);
contact.setFirstName(firstName);
contact.setPhone(phone);
}
For make sure your checks are called you can call setter methods in your constructor like this
public Contact(String contactId, String firstName, String phone) {
setFirstName(firstName);
setPhone(phone);
setContactId(contactId);
}
And check your values into setter methods
public void setFirstName(String firstName) {
if (firstName == null || firstName.length() > 10) {
throw new IllegalArgumentException("invalid first name");
}
this.firstName = firstName;
}
public void setPhone(String phone) {
if (phone == null || phone.length() != 10) {
throw new IllegalArgumentException("invalid phone number");
}
this.phone = phone;
}
public void setContactId(String contactId) {
if (contactId == null || contactId.length() > 10) {
throw new IllegalArgumentException("invalid contact ID");
}
this.contactId = contactId;
}
Furthermore, you can improve your performance using an HashMap instead of ArrayList, so that you don't need to iterate whole the list every time you need a contact.
private final Map<String, Contact> contactList = new HashMap<>();
public Contact getContact(String ID) {
return contactList.get(ID);
}
//adds a contact to the contactList array
public Contact addContact(String firstName, String Phone) {
Id++;
String contactId = Integer.toString(Id);
Contact contact = new Contact(contactId, firstName, Phone);
return contactList.put(contactId, contact);
}
As #Atryom noted, you can add the same null and length checks that you have in your constructor to your setter methods. There's no restriction specifying that your setters cannot have those checks.
I'm trying to learn the array object in Java but don't understand. I did understand how to store input into an array object but fail to understand how to compare each items inside an array to do #7 and #8. I tried to search up on the internet but stuck from there.
Create a class Student with following attributes: Name, Age, Address, Email address
Create an empty constructor that initializes empty values to all the attributes.
Create a constructor that takes all the parameters and initializes all the attributes with it.
Create accessor and mutator methods for all attributes.
Create a toString method to return the details of the student.
Ask the user to enter the details of any 5 students and store them in an array.
Ask the user to enter an address and print all the students who live in that address.
Print all the students whose email address contains “gmail.com”.
import java.util.*;
public class Student{
private String name;
private int age;
private String address;
private String email;
public Student(){}
public Student(String name, int age, String address, String email){
this.name = name;
this.age = age;
this.address = address;
this.email = email;
}
public void setName(String newName){
name = newName;
}
public void setAge(int newAge){
age = newAge;
}
public void setAddress(String newAddress){
address = newAddress;
}
public void setEmail(String newEmail){
email = newEmail;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public String getAddress(){
return address;
}
public String getEmail(){
return email;
}
public String toString() {
return "Name: " + name + ", Age: " + age + ", Address: " + address + ", Email: " + email;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Student[] s= new Student[];5
for(int i = 0; i < 5; i++){
System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Age: ");
int age = sc.nextInt();
System.out.print("Address: ");
sc.nextLine();
String address = sc.nextLine();
System.out.print("Email: ");
String email = sc.nextLine();
s[i] = new Student(name,age,address,email);
}
for(int i = 0; i < s.size(); i++){
if(s)
}
System.out.println(Arrays.toString(s));
}
}
For 7, use the scanner to retrieve a string from the user, then compare it to each user's address
System.out.print("Please enter an address: ");
String anyAddress = sc.nextLine();
for (int i = 0; i < s.length; i++) {
if (s[i].getAddress().equals(anyAddress))
System.out.println(s[i]);
}
For 8, it's quite the same, iterate on the student (I show there a for-each loop), then verify if "gmail.com"is in their email, if true, then print it
for (Student student : s) {
if (student.getEmail().contains("gmail.com"))
System.out.println(student);
}
Table Format
I have to create a program that sorts all employees by last name and prints them to the screen in a tabular format.
I am having an issue creating a table in the format attached above. Please see what I have and can help out, at this point I don't know how to set it up so the final output looks like the table attached. Thank you.
public static void main(String[] args)
{
Employee[] employees = {
new Employee("John","Johnson","Manager",20161231),
new Employee("Tou","Xiong","Software Engineer",20161005),
new Employee("Michaela", "Michaelson", "District Manager", 20151219),
new Employee("Jake","Jacobson","Programmer",00000000),
new Employee("Jackquelyn", "Jackson", "DBA",00000000),
new Employee("Sally","Webber","Web Developer",20151218)
};
// get List view of the Employees
List<Employee> list = Arrays.asList(employees);
// display all Employees
System.out.println("Complete Employee list:");
list.stream().forEach(System.out::println);
// Functions for getting first and last names from an Employee
Function<Employee, String> byFirstName = Employee::getFirstName;
Function<Employee, String> byLastName = Employee::getLastName;
// Comparator for comparing Employees by first name then last name
Comparator<Employee> lastThenFirst =
Comparator.comparing(byLastName).thenComparing(byFirstName);
// sort employees by last name, then first name
System.out.printf(
"%nEmployees in ascending order by last name then first:%n");
list.stream()
.sorted(lastThenFirst)
.forEach(System.out::println);
}
}
class Employee
{
private String firstName;
private String lastName;
private String department;
private double separationDate;
// constructor
public Employee(String firstName, String lastName,
String department,double separationDate)
{
this.firstName = firstName;
this.lastName = lastName;
this.department = department;
this.separationDate=separationDate;
}
// set firstName
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
// get firstName
public String getFirstName()
{
return firstName;
}
// set lastName
public void setLastName(String lastName)
{
this.lastName = lastName;
}
// get lastName
public String getLastName()
{
return lastName;
}
// set department
public void setDepartment(String department)
{
this.department = department;
}
// get department
public String getDepartment()
{
return department;
}
public void setseparationDate(double separationDate)
{
this.separationDate = separationDate;
}
// get salary
public double getseparationDate()
{
return separationDate;
}
// return Employee's first and last name combined
public String getName()
{
return String.format("%s %s", getFirstName(), getLastName());
}
// return a String containing the Employee's information
#Override
public String toString()
{
return String.format("%-8s %-8s %s %8.0f",
getFirstName(), getLastName(), getDepartment(),getseparationDate());
}
}```
You can accomplish this by using a combination of the String#format() method and the System.out.printf() method for formatting your particular Strings to the console window.
First it would be nice if you modify your Employee class so that the separationDate is of int type and not of double type. This would of course also include the Constructor as well as the Getter and Setter methods for this class instance variable. Adding a Getter method to your Employee class to convert this integer value to a string date format wouldn't be a bad idea either or just use a date string altogether instead of a numerical value for your separationDate instance variable. Never the less... your class could be modified to something like this where either or could be acquired:
public class Employee {
private String firstName;
private String lastName;
private String department;
private int separationDate;
// constructor
public Employee(String firstName, String lastName,
String department, int separationDate) {
this.firstName = firstName;
this.lastName = lastName;
this.department = department;
this.separationDate = separationDate;
}
// set firstName
public void setFirstName(String firstName) {
this.firstName = firstName;
}
// get firstName
public String getFirstName() {
return firstName;
}
// set lastName
public void setLastName(String lastName) {
this.lastName = lastName;
}
// Get Employee Full Name
public String getFullName() {
return this.firstName + " " + this.lastName;
}
// get lastName
public String getLastName() {
return lastName;
}
// set department
public void setDepartment(String department) {
this.department = department;
}
// get department
public String getDepartment() {
return department;
}
public void setseparationDate(int separationDate) {
this.separationDate = separationDate;
}
// Get Separation Date (As String)
public String getseparationDate() {
String dateString = "";
if (this.separationDate != 0) {
String date = String.valueOf(this.separationDate);
dateString = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8);
}
return dateString;
}
public int getseparationDateAsInt() {
return this.separationDate;
}
// return Employee's first and last name combined
public String getName() {
return String.format("%s %s", getFirstName(), getLastName());
}
// return a String containing the Employee's information
#Override
public String toString() {
return new StringBuilder(firstName).append(", ").append(lastName).append(", ")
.append(department).append(", ").append(separationDate).toString();
}
/**
* Similar to the toString() method except it will return an object instance
* as string in a table style format.<br>
*
* #param options (Optional - Boolean - Two Options)<pre>
*
* addHeader - If true is supplied then the Object instance string
* id prefixed with an underlined Header String. If
* null or nothing is supplied then no header is
* provided.
*
* addFinalUnderline - If true is supplied then an underline is added to
* the Onject instance string. If null or nothing is
* supplied then no underline is provided under the
* table. If this optional parameter is supplied then
* a boolean value (or null) <u>must</u> be supplied to the
* 'addHeader' parameter.</pre>
*
* #return (String) An Object instance String. A toString in table style format.
*/
public String toTableString(Boolean... options) {
boolean addHeader = false;
boolean addFinalUnderline = false;
if (options.length > 0) {
if (options.length >= 1 && options[0] != null) {
addHeader = options[0];
}
if (options.length >= 2 && options[1] != null) {
addFinalUnderline = options[1];
}
}
String ls = System.lineSeparator();
StringBuilder sb = new StringBuilder("");
String header = String.format("%-25s| %-20s| %-15s", "Name", "Position", "Separation Date");
String underline = String.join("", java.util.Collections.nCopies(header.length(), "-"));
if (addHeader) {
sb.append(underline).append(ls);
sb.append(header).append(ls);
sb.append(underline).append(ls);
}
sb.append(String.format("%-25s| %-20s| %-15s", getName(),
getDepartment(), getseparationDate()));
if (addFinalUnderline) {
sb.append(ls).append(underline);
}
return sb.toString();
}
}
Your instances of Employee are held as elements within the Employee Array named employees and now you want to sort them. This can be done with the java.util.Arrays.sort() method, for example:
java.util.Arrays.sort(employees, new java.util.Comparator<Employee>() {
#Override
public int compare(Employee first, Employee second) {
return first.getName().compareTo(second.getName());
}
});
Since you have already created the getName() method (which is used to compare in the above code) within the Employee class the sort would take care of first and last name sorting should last names be the same.
You're already familiar with the String formatting methods so I'm not going to bore you with that anymore. To get the table you want ( or similar to it) then you can do it this way:
Employee[] employees = {
new Employee("John", "Johnson", "Manager", 20161231),
new Employee("Tou", "Xiong", "Software Engineer", 20161005),
new Employee("Michaela", "Michaelson", "District Manager", 20151219),
new Employee("Jake", "Jacobson", "Programmer", 00000000),
new Employee("John", "Jackson", "Coffee Mole", 20161012),
new Employee("Jackquelyn", "Jackson", "DBA", 00000000),
new Employee("Sally", "Webber", "Web Developer", 20151218)
};
// Sort the above Object Array (employees) by the employee's first name.
java.util.Arrays.sort(employees, new java.util.Comparator<Employee>() {
#Override
public int compare(Employee first, Employee second) {
return first.getName().compareTo(second.getName());
}
});
// Build the Header string
String header = String.format("%-25s| %-20s| %-15s", "Name", "Position", "Separation Date");
// Build the Header Underline string
String underline = String.join("", java.util.Collections.nCopies(header.length(), "-"));
System.out.println(underline);
System.out.println(header);
System.out.println(underline);
// Build the table data strings
for (Employee empl : employees) {
System.out.printf("%-25s| %-20s| %-15s%n", empl.getName(),
empl.getDepartment(), empl.getseparationDate());
}
System.out.println(underline); // Table underline to indicate End Of Table
The Console Window should display:
------------------------------------------------------------------
Name | Position | Separation Date
------------------------------------------------------------------
Jackquelyn Jackson | DBA |
Jake Jacobson | Programmer |
John Jackson | Coffee Mole | 2016-10-12
John Johnson | Manager | 2016-12-31
Michaela Michaelson | District Manager | 2015-12-19
Sally Webber | Web Developer | 2015-12-18
Tou Xiong | Software Engineer | 2016-10-05
------------------------------------------------------------------
In the above Employee class code, you may have noticed a method added named toTableString(). This method was added to the class to assist with displaying Employee object instances in a table format to the console Window (read the method's javadoc). It could be used something like this:
Employee[] employees = {
new Employee("John", "Johnson", "Manager", 20161231),
new Employee("Tou", "Xiong", "Software Engineer", 20161005),
new Employee("Michaela", "Michaelson", "District Manager", 20151219),
new Employee("Jake", "Jacobson", "Programmer", 00000000),
new Employee("John", "Jackson", "Coffee Mole", 20161012),
new Employee("Jackquelyn", "Jackson", "DBA", 00000000),
new Employee("Sally", "Webber", "Web Developer", 20151218)
};
// Sort the above Object Array (employees) by the employee's first name.
java.util.Arrays.sort(employees, new java.util.Comparator<Employee>() {
#Override
public int compare(Employee first, Employee second) {
return first.getName().compareTo(second.getName());
}
});
// Display the table in Console Window.
int cnt = 1;
for (Employee empl : employees) {
if (cnt == 1) {
System.out.println(empl.toTableString(true));
}
else {
if ((cnt) == employees.length) {
System.out.println(empl.toTableString(null, true));
}
else {
System.out.println(empl.toTableString());
}
}
cnt++;
}
The Console Window should display:
------------------------------------------------------------------
Name | Position | Separation Date
------------------------------------------------------------------
Jackquelyn Jackson | DBA |
Jake Jacobson | Programmer |
John Jackson | Coffee Mole | 2016-10-12
John Johnson | Manager | 2016-12-31
Michaela Michaelson | District Manager | 2015-12-19
Sally Webber | Web Developer | 2015-12-18
Tou Xiong | Software Engineer | 2016-10-05
------------------------------------------------------------------
I'm trying to get a contact list created in Java. I think I have most of it, though I'm sure it could be enhanced. I believe I can add items to the arraylist, however, when I try to print the arraylist I'm getting some random text and numbers. Also, I'm not kind of lost on identifying by a contact id number and then just printing that contact. Any help or reference to material would help a lot! I've tried going through text books and researching online, and to be honest, now I'm just more confused. Here's my code:
Main:
package contactslist;
import java.util.*;
import java.io.*;
public class ContactsList {
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
int type = 0;
ArrayList<Contacts> contacts = new ArrayList<Contacts>();
while(type != 4){
System.out.println("[1] Personal Contact");
System.out.println("[2] Business Contact");
System.out.println("[3] Display Contacts");
System.out.println("[4] to quit");
type = input1.nextInt();
if(type == 4){
System.out.println("Goodbye");
break;
}
else if (type == 3){
int totalContacts = contacts.size();
for (int i = 0; i < totalContacts; i++){
System.out.print(contacts);
}
}
Scanner inputs = new Scanner(System.in);
System.out.println("Please enter a numeric ContactId: ");
String contactId = inputs.nextLine();
System.out.println("Please enter First Name: ");
String firstName = inputs.nextLine();
if (firstName == null) {
break;
}
System.out.println("Please enter Last Name: ");
String lastName = inputs.nextLine();
if (lastName == null) {
break;
}
System.out.println("Please enter Address: ");
String address = inputs.nextLine();
System.out.println("Please enter Phone Number: ");
String phoneNumber = inputs.nextLine();
System.out.println("Please enter Email Address: ");
String emailAddress = inputs.nextLine();
if(type == 1){
System.out.println("Please enter Birthday: ");
String dateofBirth = inputs.nextLine();
Contacts personal = new PersonalContact(contactId, firstName, lastName, address,
phoneNumber, emailAddress, dateofBirth);
contacts.add(personal);
}
else if(type == 2){
System.out.println("Please enter Job Title: ");
String jobTitle = inputs.nextLine();
System.out.println("Please enter Organization: ");
String organization = inputs.nextLine();
Contacts business = new BusinessContact(contactId, firstName, lastName,
address, phoneNumber, emailAddress, jobTitle, organization);
contacts.add(business);
}
}
}
}
Contacts Class:
package contactslist;
import java.util.*;
import java.io.*;
public abstract class Contacts {
String contactId;
String firstName;
String lastName;
String address;
String phoneNumber;
String emailAddress;
public Contacts(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;
}
public void displayContacts(){
System.out.println("Contact ID: " + contactId + " First Name: " + firstName + "
Last Name: " + lastName);
}
}
Personal Subclass:
package contactslist;
import java.util.*;
import java.io.*;
public class PersonalContact extends Contacts{
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);
}
}
Business Subclass:
package contactslist;
public class BusinessContact extends Contacts{
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 jobTitle(String input){
this.jobTitle = jobTitle;
}
public String getjobTitle(){
return this.jobTitle;
}
public void organization(String input) {
this.organization = organization;
}
public String getOrganization(){
return this.organization;
}
#Override
public void displayContacts(){
System.out.print("Personal Contacts: ");
System.out.println("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("Job Title: " + jobTitle);
System.out.println("Orgnanization: " + organization);
}
}
And here's what prints when I choose option 3, to display the contacts.
Error:
[contactslist.PersonalContact#1df38fd]
Any help would be greatly appreciated. I'm going crazy, and please forgive me for the question. I've tried a few different things that I've googled, and I'm just not getting it. Can someone point me in the right direction, or give me a good site to reference?
You need to code your own method to print that ArrayList. Something like :
public void printAllContacts(ArrayList<Contacts> contacts) {
for (Contacts c : contacts) {
c.displayContacts();
}
}
and call that instead of System.out.println(contacts); (Java will only print information about that object) for option 3.
Read more about ArrayList here : https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
This is my ID program which stores first name, last name, date and place on birth, email and phone number. How do I make and store a person object with only valid birth date, email and phone number (instead of having all the attributes)?
This is my main ID program:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ID {
static List<Oseba> id = new ArrayList<Oseba>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0;
int choice = 0;
boolean isDate = false;
String regEx_Email = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
String regEx_Date = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
System.out.println("How many IDs would you like to enter? ");
max = sc.nextInt();
System.out.println(" 0. Exit. ");
System.out.println(" 1. Add contact. ");
System.out.println(" 2. Outprint all contacts. ");
choice = sc.nextInt();
while (choice != 0) {
switch (choice) {
case 0:
System.out.println("Goodbye!");
System.exit(0);
case 1:
while (choice != 2) {
System.out.println("Enter First Name: ");
String firstName = sc.next();
System.out.println("Enter Last Name: ");
String lastName = sc.next();
System.out.println("Enter date of birth (dd-mm-yyyy): ");
String date = sc.next();
isDate = date.matches(regEx_Date);
System.out.println("Enter place of birth: ");
String place = sc.next();
System.out.println("Enter email: ");
String email = sc.next();
Pattern p = Pattern.compile(regEx_Email);
Matcher m = p.matcher(email);
if (m.find()) {
System.out.println(email + " is a valid email address.");
} else {
System.out.println(email + " is a invalid email address");
}
System.out.println("Enter phone number:");
String phone = sc.next();
addID(firstName, lastName, date, place, email, phone);
}
break;
case 2:
System.out.println("\n" + ID.id);
break;
default:
System.out.println("Try again.");
break;
}
System.out.println(" 0. Exit. ");
System.out.println(" 1. Add contact. ");
System.out.println(" 2. Outprint all contacts. ");
choice = sc.nextInt();
}
}
private static void addID(String firstName, String lastName, String date, String place, String email, String phone) {
Person p = new Person(firstName, lastName, date, place, email, phone);
id.add(p);
}
}
And my Person class:
class Person {
String firstName;
String lastName;
String date;
String place;
String email;
String phone;
public Person(String firstName, String lastName, String date, String place, String email, String phone) {
this.firstName = firstName;
this.lastName = lastName;
this.date = date;
this.place = place;
this.email = email;
this.phone = phone;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String toString() {
return "First Name: " + firstName + "\n"
+ "Last Name: " + lastName + "\n"
+ "Date of birth: " + date + "\n"
+ "Place of birth: " + place + "\n"
+ "Email: " + email + "\n"
+ "Phone number: " + phone + "\n\n";
}
}
Thanks for the help.
The best approach would be to break down your problem into smaller ones. For example, in order to validate the input, what you will have to do, instead of calling the setter directly is to create a method that will be responsible to validate the input for every single case. Try to use this approach everywhere since low coupling and high cohesion is always a requirement! I will provide an example on your implementation, however, there are multiple ways to do that. Also I wont use exceptions since I noticed that you are still in the beginning.
Apart from that, in order for this to work, you should add a default constructor(the values are predifined) in the Person Class.
Finally, eventhough the approach with multiple while loops is not recommented because it makes the code more complicated, I used it in order to demonstrate you how you can make sure that you will get the correct input, for example if the user input doesnt get validated, then the program will continue to ask the user until it will get the correct input. Additionally, when the user makes a mistake, directions should be provided in order to guide him/her. (this is normally done with exceptions, in our case though we provide this with simple console prints).
So let's see:
public class ID {
static List<Oseba> id = new ArrayList<Oseba>();
\*we create the menu like that in order to avoid multiple lines repetitions *\
private static String menuOptions = "Menu:" + "\nExit - Insert 0"
+ "\nAdd contact - Insert 1" + "\nExit Outprint all contacts - Insert 2";
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0;
int choice = 0;
boolean isDate = false;
System.out.println("How many IDs would you like to enter? ");
max = sc.nextInt();
Person p = new Person();
while (true) {
print(menuOptions);
choice = sc.nextInt();
switch (choice) {
case 0:
System.out.println("Goodbye!");
System.exit(0);
case 1:
while(true){
String fname = getString("Enter First Name: ");
if(verifyName(fname)){
p.setFirstName(fname);
break;
}
}
while(true){
String lname = getString("Enter Last Name: ");
if(verifyName(lname)){
p.setLastName(lname);
break;
}
}
while(true){
String date = getString("Enter date of birth (dd-mm-yyyy): ");
if(verifyBirthDate(date)){
p.setDate(date);
break;
}
}
while(true){
String birthPlace = getString("Enter place of birth: ");
if(verifyBirthPlace(birthPlace)){
p.setPlace(birthPlace);
break;
}
}
while(true){
String email = getString("Enter email address: ");
if(verifyEmail(email)){
p.setEmail(email);
break;
}
}
while(true){
String phoneNumber = getString("Enter phone number: ");
if(verifyPhoneNumber(phoneNumber)){
p.setPhone(phoneNumber);
break;
}
}
addID(p);
break;
case 2:
System.out.println("\n" + ID.id);
break;
default:
System.out.println("Try again.");
break;
}
print(menuOptions);
choice = sc.nextInt();
}
}
private static void addID(Person prs) {
id.add(prs);
}
public static Boolean verifyName(String name) {
if(!name.matches("[a-zA-Z]+")){
print("\nERROR_MESSAGE:____________The first/last name should contain only letters, everything else is not valid!");
return false;
}else{
return true;
}
}
public static Boolean verifyBirthDate(String date) {
String regEx_Date = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
if(!date.matches(regEx_Date)){
print("\nERROR_MESSAGE:____________The birth date is not valid!");
return false;
}else{
return true;
}
}
public static Boolean verifyBirthPlace(String birthPlace) {
if(!birthPlace.matches("[a-zA-Z]+")){
print("\nERROR_MESSAGE:____________The birth place is not valid!");
return false;
}else{
return true;
}
}
public static Boolean verifyEmail(String email) {
String regEx_Email = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern p = Pattern.compile(regEx_Email);
Matcher m = p.matcher(email);
if(!m.find()){
print("\nERROR_MESSAGE:____________"+email+" is an invalid email address");
return false;
}else{
return true;
}
}
public static Boolean verifyPhoneNumber(String phoneNumber) {
if(!phoneNumber.matches("[0-9]+")){
print("\nERROR_MESSAGE:____________The phone No. should contain only numbers, everything else is not valid!");
return false;
}else{
return true;
}
}
public static String getString(String msg) {
Scanner in = new Scanner(System.in);
print(msg);
String s = in.nextLine();
return s;
}
public static void print(String s) {
System.out.println(s);
}
}
Create a constructor like this
public Person(String date, String email, String phone) {
this.date = date;
this.email = email;
this.phone = phone;
}
You could optionally add
this.firstName = null;
this.lastName = null;
//for all of your fields.
You also need to uodate your getters and toString method to check if the field has been initialized. For example, for your getFirstName()
if (firstName!=null)
return firstName;
return "";
May better name for isDate field is isValidDate.
Can you use simple if statement:
if(isValidDate && m.find())
addID(firstName, lastName, date, place, email, phone);
Or can you create method for checking validation:
private boolean isValidDate(String date){
if(number!=null && number!=""){
String regEx_Date = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
return date.matches(regEx_Date);
}
return false;
}
Have you ever heard about Primitive Obsession?
I would use a Date (JodaDate) instead of String for birth date.
I would create an Email value object, throwing an IllegalArgumentException if the String provided isn't a valid email (validated by regexp).
I would create a Phone value object, throwing an IllegalArgumentException if the String provided isn't a valid phone number.
The constructor becoming:
public Person(String firstName, String lastName, Date birthDate, String place, Email email, Phone phone)
For instance, the Email object would be:
public class Email {
private String value;
public Email(String email) {
if(isNotValid(email))
throw new IllegalArgumentException("Your mail is not valid!");
this.value = email;
}
public final String getValue(){
return email;
}
private boolean isNotValid(){
//return false if email regexp validation is not verified
}
//....equals - hashcode if needed here
}
Thus, your Person would always be a valid person.
Indeed, checking that its components are valid is then the responsibility of the client, not the Person directly. It's more informative for the reader what a Person expects, just by reading the API.
Add a new boolean variable to keep track valid inputs. If all inputs are valid then only add Person object to ArrayList
boolean isValid=true;
if (m.find()) {
System.out.println(email + " is a valid email address.");
} else {
isValid=false;
System.out.println(email + " is a invalid email address");
}
if(isValid)
{
//Do other check phone number and valid birth date similarly
}
if(isValid)
{
addID(firstName, lastName, date, place, email, phone);
}