Storing Information in an Address Book - java

I am required to make an address book application without the use of databases (on memory). I have decided to use ArrayLists to do so. But the problem is that once I input a new name/contact, it overrides any other contacts that I "stored" (or thought I stored) before. I have been trying to figure it out and am outright confused.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
firstActions();
}
static String firstName;
static String lastName;
static String phoneNumber;
static String search = null;
static public int choice = 0;
static Scanner input = new Scanner (System.in);
static ContactInformation contact;
static ArrayList<String> information = new ArrayList<String>();
public static void firstActions()
{
System.out.println("Address Book Menu: What would you like to do? 1) Input data. 2) Search data. 3) Close.");
choice = input.nextInt();
switch (choice) {
case 1:
inputData();
case 2:
System.out.println("Search by: 1) First Name 2) Last Name 3) Phone Number 4) Zip Code.");
choice = input.nextInt();
switch (choice) {
case 1:
searchName();
break;
case 2:
searchLastName();
case 3:
searchPhoneNumber();
case 4:
//execute search by Zip Code
default:
System.out.println("Please compile again.");
break;
}
break;
case 3:
System.out.println("Application terminated.");
System.exit(0);
default:
System.out.println("Please compile again.");
break;
}
}
public static void inputData ()
{
information = new ArrayList<String>();
contact = new ContactInformation(firstName, lastName, phoneNumber, information);
System.out.println("What is your first name?");
contact.setFirstName(input.next());
information.add(contact.getFirstName());
System.out.println("What is your last name?");
contact.setLastName(input.next());
information.add(contact.getLastName());
System.out.println("What is your phone number?");
contact.setPhoneNumber(input.next());
information.add(contact.getPhoneNumber());
System.out.println("Saved.");
System.out.println("What would you like to do next?");
firstActions();
}
public static void searchName()
{
System.out.println("What is the first name you are looking for?");
search = input.next();
if (search.equals(information.get(0)))
{
System.out.println(information);
System.out.println("What would you like to do next?");
firstActions();
}
else
{
System.out.println("This person is not saved in the address book. Please try again.");
firstActions();
}
}
public static void searchLastName()
{
System.out.println("What is the last name you are looking for?");
search = input.next();
if (search.equals(information.get(1)))
{
System.out.println(information);
firstActions();
}
else
{
System.out.println("This person is not saved in the address book. Please try again.");
firstActions();
}
}
public static void searchPhoneNumber()
{
System.out.println("What is the last name you are looking for?");
search = input.next();
if (search.equals(information.get(2)))
{
System.out.println(information);
firstActions();
}
else
{
System.out.println("This person is not saved in the address book. Please try again.");
firstActions();
}
}
}
Here is my contact information class:
import java.util.ArrayList;
public class ContactInformation {
public String firstName;
public String lastName;
public String phoneNumber;
ArrayList <String> information = new ArrayList<String> ();
public ContactInformation(String firstName, String lastName,
String phoneNumber, ArrayList<String> information) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.information = information;
}
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 getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}

You first create the ArrayList here:
static ArrayList<String> information = new ArrayList<String>();
but every time you go to the inputData() method, you create a NEW ArrayList:
information = new ArrayList<String>();
From how you wrote the code, I would assume you have a ContactInformation object that you should be placing into the ArrayList.
Change the ArrayList to: static ArrayList<ContactInformation> information = new ArrayList<ContactInformation>();
Then you can create each object and ADD the object to the ArrayList INSTEAD of all the information separately.
EDIT:
Your "ContactInformation" object contains String variables. After you add this object to the ArrayList, you can use a loop to find if the data in the object matches what you are looking for. It should look something like this:
for (int i = 0; i != information.size(); i++) {
if (information.get(i).getFirstName().matches(search)) {
System.out.println("found");
}
}
The if statement says that "if the element 'i's variable 'firstName' in ArrayList 'information' matches the variable 'search', print the word 'found'."
You can obviously change what happens if the name is found, I just simplified it.

everytime you want to insert a name you are creating a new Object from ArrayList
information = new ArrayList<String>();
initizalize this arraylist in your main method and then access it via its variable(information)

The immediate problem is with the first line in your inputData() method:
information = new ArrayList<String>();
You're creating a new ArrayList object every time the method is called, which means the old object, and the data it contained, is lost.

Related

Use an arraylist multiple times inside different parts of JAVA code

I am using an array list to store values from user input by constructing an interactive menu for them to choose. My two choices so far, provides the user to input data to the list and to read the whole content of a list. The code I created so far consists of two classes.
My main class,
package com.andrekreou;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome to the personnel address book");
System.out.println("In the following menu, a whole selection of services is provided");
Scanner user_input = new Scanner(System.in);
while (true){
showMenu();
String selection = user_input.next();
if (selection.equals("1")){
System.out.println("Below you can see all of the data being provided");
for (String personnel : catalog) { } //ERROR: Cannot resolve symbol catalog
}else if (selection.equals("2")){
ArrayList<String> catalog = new ArrayList<>();
Personnel p1 = new Personnel();
System.out.println("Please insert the data for the new contact");
System.out.println("Input the fullname:");
Scanner scan = new Scanner(System.in);
String full_name = scan.nextLine();
p1.setFull_name(full_name);
catalog.add(full_name);
System.out.println("You inserted the following fullname: "+p1.getFull_name());
System.out.println("Input the phonenumber:");
Scanner phone_number_input = new Scanner(System.in);
String phone_number = phone_number_input.next();
p1.setPhone_number(phone_number);
catalog.add(phone_number);
System.out.println("You inserted the following phonenumber: "+p1.getPhone_number());
System.out.println("Input the address:");
Scanner address_input = new Scanner(System.in);
String address = address_input.nextLine();
p1.setAddress(address);
catalog.add(address);
System.out.println("You inserted the following address: "+p1.getAddress());
System.out.println("Εισάγετε την διεύθυνση e-mail:");
Scanner email_input = new Scanner(System.in);
String email = email_input.next();
p1.setEmail(email);
catalog.add(email);
System.out.println("You inserted the following e-mail: "+p1.getEmail());
System.out.println("Εισάγετε την ημερομηνία γέννησης:");
Scanner date_of_birth_input = new Scanner(System.in);
String date_of_birth = date_of_birth_input.nextLine();
p1.setDate_of_birth(date_of_birth);
catalog.add(date_of_birth);
System.out.println("You inserted the following: "+p1.getDate_of_birth());
System.out.println("Εισάγετε τον αριθμό ΑΜΚΑ:");
Scanner AMKA_input = new Scanner(System.in);
String AMKA = AMKA_input.next();
p1.setAMKA(AMKA);
catalog.add(AMKA);
System.out.println("You inserted the following ΑΜΚΑ: "+p1.getAMKA());
}
}
}
static void showMenu(){
System.out.println("1. View the whole contacts");
System.out.println("2. Insert a new contact");
System.out.println("Please give your choice");
}
}
and my personnel class with getter and setter methods in order to store the data from user input,
package com.andrekreou;
import java.io.Serializable;
public class Personnel implements Serializable {
private String full_name;
private String phone_number;
private String address;
private String email;
private String date_of_birth;
private String AMKA;
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDate_of_birth() {
return date_of_birth;
}
public void setDate_of_birth(String date_of_birth) {
this.date_of_birth = date_of_birth;
}
public String getAMKA() {
return AMKA;
}
public void setAMKA(String AMKA) {
this.AMKA = AMKA;
}
}
My problem is that I want to use the catalog list in option 1 using a foreach loop but I can't since I am getting a "Cannot resolve symbol catalog" error as showing in the code. What am I doing wrong?
I am not going to argue about the correctness of the solution, and the different way to implement it. However, if you want to solve that compilation error, it is just a matter of variable scope: You just need to move the creation of the catalog list at the beginning of the main function, in a way to increase its scope, for example you can put it as first statement, like this:
public class Main {
public static void main(String[] args) {
ArrayList<String> catalog = new ArrayList<>(); // Creation of catalog list
...
}
...
}

Java ~ User by user

I would like the user to provide data by scanner and add it to list. Later, I want to get the size of this list and for example user name, last name. I'm still trying to work with constructors and exceptions and now I want to try to put data from user.
It's Human Service which checks constructors, and if the name has less than 3 letters and lastname less than 5 letters will throw an exception.
import java.util.ArrayList;
import java.util.List;
public class HumanService {
List<Human> humans;
public HumanService() {
humans = new ArrayList<>();
}
public void addHuman(String name, String lastName) throws HumanNameWrongFormat, HumanLastNameWrongFormat {
if(HumanValidator.humanValidatorName(name) && HumanValidator.humanValidatorLastName(lastName)) {
Human human = new Human(sizeOfList(), name, lastName);
humans.add(human);
}
}
public int sizeOfList() {
return humans.size();
}
public Human getHumanByLastName(String lastName) throws HumanNotFoundException {
for (Human human : humans) {
if (human.getLastName().equals(lastName)) {
return human;
}
}
throw new HumanNotFoundException(lastName + " not found");
}
public Human getHumanById (Integer id) throws HumanNotFoundException {
for (Human human : humans) {
if (human.getId().equals(id)) {
return human;
}
}
throw new HumanNotFoundException(id + " not found");
}
}
I want to get data by user to list.
For example.
Please give me your name and last name.
Here is your name and last name by scanner and that will be added to list and checked.
This is also my main class.
public class main {
public static void main(String[] args) throws HumanNotFoundException {
HumanService humanService = new HumanService();
try {
humanService.addHuman("John", "Walker");
humanService.addHuman("Steve", "Williams");
humanService.addHuman("Gregor", "Wroten");
}
catch (HumanNameWrongFormat | HumanLastNameWrongFormat e) {
System.out.println(e.getMessage());
}
System.out.println(humanService.sizeOfList());
try {
humanService.getHumanByLastName("Wroten");
}
catch (HumanNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
Here is the way you can use Scanner to get all the required user names and add them to the list for further processing
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Human> humans = new ArrayList();
while (true) {
System.out.println("Please give your first name");
String firstName = scanner.nextLine();
System.out.println("Please give your last name");
String lastName = scanner.nextLine();
humans.add(new Human(firstName, lastName)); // use your humanService here
boolean breakOut = false;
String input;
do {
System.out.println("Do you want to enter more names? (Y/N)");
input = scanner.nextLine();
if (input.equalsIgnoreCase("Y") || input.equalsIgnoreCase("N")) {
breakOut = true;
} else {
System.out.println("Invalid input. try again");
}
} while (!breakOut);
if (input.equalsIgnoreCase("Y")) {
break;
}
}
System.out.println(humans);
}
}
I am assuming you have two fields firstName, lastName in Human
class Human {
private String firstName;
private String lastName;
public Human(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
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;
}
#Override
public String toString() {
return "first name " + firstName + " and last name " + lastName;
}
}
Input:
Please give your first name
John
Please give your last name
Smith
Do you want to enter more names? (Y/N)
y
Please give your first name
Will
Please give your last name
Smith
Do you want to enter more names? (Y/N)
n
Output:
[first name John and last name Smith, first name Will and last name Smith]
In the above code, replace the list with your humanService to add the humans

Error when trying to add user input to an array

I am quite new to java and am having a problem trying to store user input to an array to later be able to call the list, however I am getting an error when trying to do so. The error comes on the newvoter.add(); line. Sorry if I'm being ignorant in any way, I feel like I'm being stupid!
public class admin {
public static Scanner sc = new Scanner (System.in);
public static List<voter> Voters = new ArrayList<voter>();
public static int promptUserInput() {
System.out.print("\n\tEnter: ");
int option = sc.nextInt();
return option;
}
public static int getOption() {
int option = promptUserInput();
switch(option){
case 1:
addVoter();
break;
case 2:
//deleteVoter();
break;
case 3:
Questions openQuestions = new Questions();
openQuestions.addQuestion();
break;
case 4:
break;
case 5:
System.out.println("Programme Ended");
System.exit(0);
default:
break;
}
return option;
}
public static void main(String[] args) {
printMenu();
}
public static void printMenu(){
System.out.println("\nAdmin Options Menu\n"
+ "\t\nPlease enter an option:\t\n"
+ "\n\t\t1: Create Voter\t\n"
+ "\t\t2:Delete Voter\t\n"
+ "\t\t3:Add Questions\t\n"
+ "\t\t4: View Questions List\t\n"
+ "\t\t5: Delete Question\t\n");
getOption();
}
private static void addVoter(){
voterAdd newvoter = new voterAdd(); // Creates a new voter
System.out.println("Enter First Name: ");
String firstName = sc.next();
System.out.println("Enter Surname Name: ");
String surname = sc.next();
System.out.println("Enter Voter ID: ");
int voterID = sc.nextInt();
System.out.println("Enter City: ");
String city = sc.next();
newvoter.setVoter(firstName, surname, voterID, city);//calls the 'setVoter' method inherited from 'voter'
newvoter.add();//adds the 'newVoter' to the ArrayList 'voter'
System.out.println("\n New voter identification has been created and stored.\n");
listVoters();
}
Here is the class it calls from..
public class voterAdd {
private String firstName = "";
private String surname = "";
private int voterID = 0; //voterID of the voter
private String city = "";
public void setVoter(String firstName, String surname, int voterID, String city) {
this.firstName = firstName;
this.surname = surname;
this.voterID = voterID;
this.city = city;
}
public String getFirstName()
{
return firstName;
}
public String getsurname()
{
return surname;
}
public int getID()
{
return voterID;
}
public String getCity()
{
return city;
}
}
It's Voters.add(newvoter);, not newvoter.add(). Also, variable names should start with a lowercase letter or an underscore. Classes should start with uppercases.
Well one of your problems is that you are calling in your List the voter class, when maybe it should be the voteradd class like such:
List<voteradd> listName = new List<voteradd>();
Another thing, common java principles expect java classes to start with a capital letter(camel case), it's just good conventions and good practice. Hopefully this helped, best of luck :)

How to create a search method for an array

My code is as follows:
import java.io.*;
import java.util.*;
public class readStudents extends Object
{
private String SName = "";
private String DoB = "";
private String Gender = "";
private String Address = "";
Student [] students = new Student[20];
public void fillStudentArray()
{
// properties
int size; // total number of Students in collection
File file = new File("StudentDetails.txt");
try
{
Scanner in = new Scanner(file);
while(in.hasNextLine())
{
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public String getName()
{
return this.SName;
}
public void printname()
{
System.out.println("hello");
}
public Student search(String name)
{
System.out.print("Enter the name you wish to search: ");
for (int i = 0; i < this.students.length; i++)
{
Student s = this.students[i];
if (s.getName().equalsIgnoreCase(name))
{
return s;
}
}
return null;
}
} //end class students
However I am trying to create a well refined program that I can call on these methods from another main file with as minimal code as possible in that file.
The search method at the bottom is tripping me up as I am assuming I need to put something to do with the array in my getName() method but I can't figure it out.
Since I am doing this as a class for another main method, with the placement of my array initialization and declaration it allows the other methods to access it but it leaves me with no way to create this array from the main method unless I am missing something?
This is the error jCreator is throwing:
F:\University\Ass2\readStudents.java:62: error: cannot find symbol
if (s.getName().equalsIgnoreCase(name))
^
symbol: method getName()
location: variable s of type Student
You never populated the Student students[] array... You retrieved the values you would populate them with here:
while(in.hasNextLine())
{
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
}
But you never actually set those values into a Student object in the students[] array
Do something like this:
int i = 0;
while(in.hasNextLine())
{
String name = in.next();
String dateOfBirth = in.next();
String gender = in.next();
String address = in.next();
students[i] = new Student(name, dateOfBirth, gender, address);
i++
}
Also, you might consider ditching the array and using some sort of List or Hash object... If your file contains more than 20 lines, the array will be out of index when you try to define the 21st value.. With an arraylist or a List you wouldn't have that problem
I took a liberty to tweak your code as previous answer mentioned, it's better to use array list in your case. You could make a small student container class within your reader. The get name method is also kinda redundant ;s
package test;
import java.io.*;
import java.util.*;
public class readStudents{
ArrayList<Student> students = new ArrayList<Student>();
class Student {
private String name;
private String dob;
private String gender;
private String address;
public Student(String name, String dob, String gender, String address) {
this.name = name;
this.dob = dob;
this.gender = gender;
this.address = address;
}
public void fillStudentArray() {
// properties
int size; // total number of Students in collection
File file = new File("StudentDetails.txt");
try {
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
students.add(new Student(SName, DoB, Gender, Address));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String getName(Student student) {
return student.name;
}
public void printname() {
System.out.println("hello");
}
public Student search(String name) {
System.out.print("Enter the name you wish to search: ");
for (Student student : students) {
if (student.name.equalsIgnoreCase(name))
;
return student;
}
return null;
}
}
}
If you're not forced by your teacher to use for or for-each cycle in the search function - this is how to do a full scan the Java 8 way
public Optional<Student> findFirstByName(final String name) {
return Arrays.stream(students)
.filter(s -> s.getName().equalsIgnoreCase(name))
.findFirst();
}

Creating a contact list with java and object oriented

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

Categories