A school assignment (in beginner Java) is asking me to create a small contact manager program, which I'm having trouble with.
It asks us to create a few classes - Address, PhoneNumber, Contact, and ContactManager.
In ContactManager, we're asked to create a method called addContact() which will add a brand new unique contact to an object array within ContactManager.
However I cannot figure out how to make this method do what I want it to do since each time it creates a new Contact, it always has the same name. How do I make the object it creates have a unique name (i.e. Contact001, Contact002 etc) each time?
Also, how do I feed through all the relevant information it needs to create it, assuming I can enter all the data in instance variables to test it?
This is my code class:
public class Contact {
//Contact Instance Variables
private String lastName;
private String firstName;
private String middleName;
private Address completeAddress[];
private PhoneNumber phoneNumer[];
private SocialNetworkAccount socialNetworkInfo[];
public Contact(String lastName, String firstName, String middleName,
Address[] completeAddress, PhoneNumber[] phoneNumer,
SocialNetworkAccount[] socialNetworkInfo) {
this.lastName = lastName;
this.firstName = firstName;
this.middleName = middleName;
this.completeAddress = completeAddress;
this.phoneNumer = phoneNumer;
this.socialNetworkInfo = socialNetworkInfo;
}
"private List contacts;" is a declaration of an instance variable called contacts.
The variable's type is a List, which is a specific kind of Collection object found in the java.util package.
List<Contact> is a way of stating to the compiler that this list contains only Contact objects. See "Generics" in the java tutorial.
In your ContactManager class, define these
private List<Contact> contacts;
contacts = new ArrayList<Contact>(); //you should put this in ContactManager constructor
public void addContact(Contact contact) {
contacts.add(contact);
}
When you want to add a new contact
//just supply different names, etc. load the information from a file
contactManager.addContact(new Contact(name,surname,....));
or...
To add a couple of placeholder contacts...
int NUM_OF_CONTACTS = 2; //how many contacts to create
for(int i = 0; i < NUM_OF_CONTACTS; ++i) {
contactManager.addContact(new Contact(("Contact" + i),"Placeholder Surname",..);
}
Related
I'm creating a simple Java app that would store and display information for customers.
I want to make the id as an automated generated number but having problems with that, don't know should I set it in get or set methods?
Can anyone help me to use that value as?
Here is an example:
public class Customer{
public Person(String firstName, String lastName, String email, String address, String country){
this.id.set(Integer.parseInt(UUID.randomUUID().toString()));
this.firstName.set(firstName);
this.lastName.set(lastName);
this.email.set(email);
this.address.set(address);
this.country.set(country);
}
private final IntegerProperty id = new SimpleIntegerProperty(this,"Id",0);
private final StringProperty firstName = new SimpleStringProperty(this,"First Name","");
private final StringProperty lastName = new SimpleStringProperty(this,"Last Name","");
private final StringProperty email = new SimpleStringProperty(this,"E-mail","");
private final StringProperty address = new SimpleStringProperty(this,"Address","");
private final StringProperty country = new SimpleStringProperty(this,"Country","");
I also created generic bean methods but it's just simple like this:
public StringProperty firstNamePropery(){
return firstName;
}
public String getFirstName(){
return firstName.get();
}
public void setFirstName(String firstName){
this.firstName.set(firstName);
}
//...rest of the methods...
I tried to use this but doesn't work:
public IntegerProperty idProperty(){
return id;
}
public Integer getId(){
return id.get();
}
public void setId(){
this.id.set(Integer.parseInt(UUID.randomUUID().toString()));
}
Thank you for helping me on this one.
A UUID string looks like this 38400000-8cf0-11bd-b23e-10b96e4ef00d. You can't parse this string into an Integer.
If you want to use UUIDs as the Ids for the customers then, declare the attribute as UUID or String instead of Integer.
EDIT I
Also, I don't need to store it as an Integer value, the string can do
job but just can't get to create that number when creating a new
instance of that class.
To use a UUID as a String:
In the Customer class the id attribute must be of type String instead of Integer (or int).
To get a new String representation of the UUID you call UUID.randomUUID().toString(). The result of this call can be assigned to the customer's id without doing any parsing.
Also note that the signatures of the getter and setter have to change accordingly.
In the current setId() method you are creating a new id. This would override the id assigned when the Customer is created using the call in the constructor. If you want flexibility to assign a new id you can have the setId receive a new UUID string and assign that as a new id to the Customer object.
public class Customer{
public Customer(String firstName, String lastName, String email, String address, String country){
this.id.set(UUID.randomUUID().toString());
}
...
public String getId(){
return this.id;
}
public void setId(String newId){
this.id = newId;
}
}
Note: The class name is Customer and the constructor is Person. This is wrong, both must have the same name. You must have some compiler error telling you this. I will assume the correct name of the class and constructor is Customer
/EDIT I
The use case for UUID is when you need to have a unique id without checking if the id already exists with some other party (for example a database engine or a server in a network application without a central server).
If what you want to use is Integer (or Long) there is no real reason to use a Random number, you can use a sequential number for your ids.
If if is a standalone application in javafx, and you are not using different threads to create customers in parallel, then there isn't much more to worry about.
On the other side if it is a client server application. Then you have take in mind the concurrent access of clients to the server.
If you delegate the id creation as a sequence in the database then, the concurrency issue or generating duplication in the id is taken care by the database itself. This could be an autoincrement field in the same customer table (assuming you are using one), a sequence, or a table acting as a sequence. On another side, if it is a class of yours which is going to generate the ids one by one, then you will have to take care of concurrent requests. You will have to make sure that only one thread can increment the id at a time.
Regarding getters and setters, getXxx() returns the value of xxx attribute. and setXxx(123) would set or assign the value 123 to the attribute xxx;
Guys this is my membership class so far, i am struggling to create a method that finds the full members details that i have given just using a uniqueId finder. Please help.
public class Membership {
private String FirstName;
private String LastName;
private int memberId;
private String listOfMembers;
private int uniqueId;
private long phoneNumber;
public Membership(String FirstName, String LastName, int uniqueId,
long phoneNumber)
{
this.uniqueId = uniqueId;
this.FirstName = FirstName;
this.LastName = LastName;
this.phoneNumber = phoneNumber;
}
public String getMember()
{
return FirstName + LastName;
}
public String getlistOfMembers()
{
return (FirstName + LastName);
}
public int getId()
{
return uniqueId;
}
public void MemberId (int Id)
{
System.out.println("Id" + Id);
}
public String getMemberDetails ()
{
System.out.println("Member Id: " + uniqueId);
System.out.println("first name: " + FirstName);
System.out.println("LastName: " + LastName);
System.out.println("Member phone number: " + phoneNumber);
return listOfMembers;
}
}
This is what i have done so far.
Issues:
You've got user interface code where it doesn't belong. I would remove all System.out.println statements from this class and instead leave it in a UI class or main method (if very simple).
In particular, getter methods should return field values, and should not have System.out.println statements
I'm not sure why this class has a listOfMembers field, or why it's just a String. You look to be trying to combine Member and Membership together in one single class -- Don't do this.
I'd name this class Member since it holds information for just a single Member.
If I needed a Membership class, it would instead hold an ArrayList<Member>
And it would have a public Member getMember(int id) method that would return the item in the list above that shares the id passed into the method. A simple for loop that iterated through the list, comparing id's would suffice.
To add on Hovercraft's answer with an example.
You have your class handling all the members, very basic implementation of it.
public class Membership {
private final Map<Integer, Member> members = new HashMap<>();
public void addMember (Integer uniqueId, Member member) {
members.put (uniqueId, member);
}
public void getMember (Integer uniqueId) {
return members.get (uniqueId);
}
...
}
Then you have the Members themselves like this, more fields can be added as you want them.
public class Member {
private String firstName;
private String lastName;
public Member (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName () {
return firstName;
}
...
}
This is a very basic, but strong, feature in OOP to use.
Again see Hovercraft's answer as it provides all the details. If they were to edit/remove I will update this one.
Map vs List
One minor thing is I'd vote against using an ArrayList<E> to store the Members. If you add to the implementation that you can remove users the uniqueId will shift from user to user. Instead I would be for making sure that you are not adding to an existing user.
If you want to keep it simple and just get going, an ArrayList<E> works, do know the problem you might get in the feature, an uniqueId is not necessarily tied to a Member.
"I am quite new to java and have never come across "map" can you please explain what it is?"
"An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value." - From: Documentation.
Instead of working with direct indexes as you do in an Array:
arr[5]; // here you get the value at index position 5.
Or like a List:
list.get(5); // here you get the fifth element, it can be stored (almost) anywhere in the memory, before or after 4, doesn't matter, as 4 knows where 5 is.
And for a Map:
map.get(5); // you get the object stored at 5, there might not be a 3 or 4 in the Map. You can store any Objects as anything. A String is another example of a common key.
I would suggest to use Map and use id as key of Map and store object of Membership as Value,thereby easy to retrieve and store also.
Something similar to this,
Map<Integer,Membership> map = new HashMap<Integer,Membership>();
Membership m = new Membership("First", "LastName", 1,1234567890);
map.put(m.getId(), m);
To get member by id,
System.out.println(map.get(id).getMemberDetails());
I'm trying to do something pretty simple but I can't seem to get it to work. I'm trying to iterate through an ArrayList but my for loop is always returning the same value when I output the results to the terminal.
Here is the code:
import java.util.*;
public class Contact{
public static ArrayList<Contact> contacts = new ArrayList<Contact>();
public static String name;
public static String phoneNumber;
public static String email;
private static int idCounter = 0;
private final int contactID;
public static void main(String[] args){
Contact bob = new Contact("bob","8493483943","jo#g.com");
Contact joe = new Contact("joe","940389439","something#g.com");
ArrayList<Contact> contacts = new ArrayList<Contact>();
contacts.add(bob);
contacts.add(joe);
for (Contact person : contacts) {
System.out.println(person.idCounter);
System.out.println(person.name);
System.out.println(person.phoneNumber);
System.out.println(person.email);
System.out.println();
}
}
public Contact(String name,String phoneNumber,String email){
this.contactID = idCounter++;
this.name = name;
this.phoneNumber = phoneNumber;
this.email = email;
}
}
The above code always returns this when I run the code:
2
joe
940389439
something#g.com
2
joe
940389439
something#g.com
It returns the same information even though I've added 2 different objects into the ArrayList.
When I do this inside the for loop:
System.out.println(person);
It returns a Contact object with different id's.
I'm a little confused as to why this is happening as I'm assuming I'm not referencing the same variable or object here, or that I'm doing something wrong in my loop.
If anyone could help me explain what's going on that'd be great, thanks!
your attributes are static: name, phoneNumber and email. Remove static keyword [static keyword make classlevel attributes] :)
All your class variables are static. This means they will be overwritten ones you create the second object.
I have a class named Customer which stores the following objects:
private String CustomerFirstName
private String CustomerLastName
private String CustomerID
private String CustomerEmail
now in order to pass data to jasper report, I decided to create an array list which contains these objects, so :
import java.util.ArrayList;
import java.util.Collection;
/* This is CustomerDataSource.java file */
public class CustomerDataSource {
public static Collection<Customer> loadCustomers() throws Exception {
Collection<Customer> customers = new ArrayList<Customer>();
Customer customer = new customer (
/* I need help getting the objects CustomerFirstName / CustomerLastName and etc */
);
customer.addBilling(new Billing ( /* Adding billing info */ ));
customer.getBilling(new Billing ( /* I need to get the object's values*/));
customer.balOwing();
customers.add (customer);
return customers;
}
}
can someone please explain how to add the objects in Customer.java to the array list? (and in general since I need to add objects from different files as well. Thank you
So as I see your problem in your comment, you want to create a constructor.
In your Costumer class
public Costumer(String firstName, String lastName, String ID, String email) {
this.CostumerFirstName = firstName;
this.CostumerLastName = lastName;
this.CostumerID = ID;
this.CostumerEmail = email;
}
So then you can create a new costumer like that:
Customer customer = new Customer ("SampleFirstName","SampleLastName","0000","address#web.com");
You could even add the costumer automatically to the ArrayList by adding it in the constructor.
From your comment, I am guessing you would like to use a constructor?
You will have to add a constructor on your Customer.java.
public Customer(String firstName, String lastName, String id, String email){
this.CustomerFirstName = firstName;
this.CustomerLastName = lastName;
this.CustomerID = id;
this.CustomerEmail = email;
}
You might want to make getter/setter methods for access to above variables.
ArrayList<E>.get(i) performs virtually the exact same function as [] in static arrays. The only difference between the two is that ArrayList<E>.get(i) is simply adapted into the object context. In other words, you can dereference it.
First, you'll need to change the privacy of Customer's fields to public to give the ArrayList<Customers> object access to it.
Then you'll be able to retrieve your class' fields with simply:
customers.get(index).FirstName //or whatever other field
My assignment is to create a basic contact list program that lets the user
Enter a new contact,
Print the contact list,
Retrieve a contact by last name,
Email, and
Retrieve contacts in a specific zip code.
My idea is to create 3 classes:
Main(), Contact(), and ContactList(). I would proceed by having the main() handle the menu and the logic. Contact() would be a class object I would instantiate for each contact. ContactList() would be the class that defines an array of Contact objects, and define methods to enter and retrieve information.
The problem is I'm not sure how to go about this. Would my approach stated above work? I'm not quite sure how to go about this and any suggestions and ideas would be greatly appreciated.
Here are my thoughts on this, with some pseudocode to help.
The following class is a basic implementation for what a contact should consist of based on the requirements. I opted for using String fields since this is just a homework problem and requires no extra engineering.
public class Contact
{
private String firstName;
private String lastName;
private String email;
private String zipCode;
public Contact()
{
//initialize all variables to empty string
}
public Contact(String firstName,String lastName, String email, String zipCode)
{
//Use this.variableName to set values
}
//getters/setters
}
public class Assignment1 //Or whatever assignment number this is == Main()
{
List<Contact> contacts;
public static void main(String[] args)
{
//Retrieve user input
// Execute rest of program
}
void printContacts(List<Contact> contacts)
{
foreach(Contact in contacts)
{
print(Contact.toString());
}
}
Contact getContactByLastName(String lastName)
{
foreach(Contact in contacts)
{
if(Contact.lastName == lastName)
return Contact;
}
else
Contact does not exist
}
void addContact(Contact contact)
{
contacts.add(contact);
}
}
I would have the ContactList only habe the required methods that make sense:
interface ContactList {
void add(Contact)
List<Contact> getList()
Contact getContactByLastName(String)
Contact getContactByEmail(String)
Contact getContactByZipCode(String)
}
then you can implement that interface with, lets say, an ContactArrayList that uses an ArrayList<Contact> for the backing object.
I would have your ContactList implement a generic list
public class ContactdList implements List<Contact>
but yeah, that sounds like it would work. I assume this is for a class, you don't want to get too far afield of what the the teacher has asked for/taught.