display an entire arraylist in java - java

I'm still pretty new to java. Am trying to make a program that basically adds contacts to an array list. I have figured everything out as far as creating a new object and setting the name/number. As far as I can tell it's adding it to the array, however I'm not sure how I can display the array? I want to add a snippet of code that would display the array list after you add each contact.
Here is my contact class, not sure if I need the PhoneBook method or not for the array....
public class Contact {
String first; //first name
String last; //last name
String phone; //phone number
String PhoneBook; //array list???
public void PhoneBook(String f, String l, String p) {
first = f;
last = l;
phone = p;
}
public void setFirst(String first) {
this.first = first;
}
public void setLast(String last) {
this.last = last;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Contact makeCopy() {
Contact Contact = new Contact();
Contact.first = this.first;
Contact.last = this.last;
Contact.phone = this.phone;
return Contact;
} //end makeCopy
} //end class Computer
Here is my driver class...
import java.util.Scanner;
import java.util.ArrayList;
public class contactDriver {
public static void main(String[] args) {
Contact Contact = new Contact(); //make default Contact
Contact newContact;
String first; //first name
String last; //last name
String phone; //phone number
String input; //answer to create a new contact
boolean add = true; //boolean to add new contact
Scanner scan = new Scanner(System.in);
Contact.setFirst("Default");
Contact.setLast("Default");
Contact.setPhone("Default");
while (add) {
System.out.println("Would you like to create a new contact? (Y/N)");
input = scan.nextLine();
if (input.equals("Y") || input.equals("y")) {
newContact = Contact.makeCopy();
System.out.println("Enter the contact's first name: ");
first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
last = scan.nextLine();
System.out.println("Enter the contact's phone number: ");
phone = scan.nextLine();
ArrayList < Contact > PhoneBook = new ArrayList();
newContact.setFirst(first);
newContact.setLast(last);
newContact.setPhone(phone);
PhoneBook.add(newContact);
} else {
add = false;
System.out.println("Goodbye!");
break;
}
}
} //end main
} //end Class ComputerDriver

If just for printing, override the toString method of your Contact class, which will be like:
#Override
public String toString() {
return first + " " + last + "; phone number: " + phone;
}
Then, in your main method, print all the contacts by doing:
for (Contact c : phoneBook) {
System.out.println(c);
}
Also, you should create the phoneBook, which is an ArrayList outside of your loop.
Your Contact class should be defined as:
public class Contact {
private String first; // first name
private String last; // last name
private String phone; // phone number
public Contact(String f, String l, String p) {
first = f;
last = l;
phone = p;
}
public String getFirst() {
return first;
}
public String getLast() {
return last;
}
public String getPhone() {
return phone;
}
public Contact makeCopy() {
return new Contact(first, last, phone);
}
#Override
public String toString() {
return first + " " + last + "; phone number: " + phone;
}
}
And your main method should be:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Contact> phoneBook = new ArrayList<>();
while (true) {
System.out.println("Would you like to create a new contact? (Y/N)");
String input = scan.nextLine();
if (input.equalsIgnoreCase("Y")) {
System.out.println("Enter the contact's first name: ");
String first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
String last = scan.nextLine();
System.out.println("Enter the contact's phone number: ");
String phone = scan.nextLine();
Contact contact = new Contact(first, last, phone);
phoneBook.add(contact);
for (Contact c : phoneBook) {
System.out.println(c);
}
} else {
System.out.println("Goodbye!");
break;
}
}
scan.close();
}

The compiler will give warning, most likely because of this:
String PhoneBook;
when you know that you also have
public void PhoneBook(String f, String l, String p)
and even more another PhoneBook
ArrayList < Contact > PhoneBook = new ArrayList();
try to use another variable name and function name to be safe and make sure they are different especially for
String PhoneBook;
public void PhoneBook(String f, String l, String p)
since they are under same class.
In terms of data structure, you have a wrong concept here. first is, this:
ArrayList < Contact > PhoneBook = new ArrayList();
should be outside the while loop so for whole your application, you will not replace your phone book after looping. to print them, later just use
for(int i = 0; i < phoneBook.size(); i++)
your printing

You just override toString() method of your Contact class, and in main() method, directly call your ArrayList's toString().
Here is my example:
package somepackage;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Inner> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Inner in = new Inner("name" + i, "address" + i);
list.add(in);
}
System.out.println(list.toString());
}
private static class Inner {
private String name;
private String address;
Inner(String name, String address) {
this.name = name;
this.address = address;
}
#Override
public String toString() {
return "name:" + name + ", " + "address: " + address + "\n";
}
}
}
Screen outputs:
[name:name0, address: address0
, name:name1, address: address1
, name:name2, address: address2
, name:name3, address: address3
, name:name4, address: address4
, name:name5, address: address5
, name:name6, address: address6
, name:name7, address: address7
, name:name8, address: address8
, name:name9, address: address9
]

Ok, figured it out thanks to your guys help! I changed the if statement so you can now add a new contact, display the phone book, or quit. I also added phone number validation! Here is the updated code if anyone cares!
import java.util.Scanner;
import java.util.ArrayList;
public class contactDriver {
public static void main(String[] args) {
String first; //first name
String last; //last name
String phone = ""; //phone number
String input; //answer to create a new contact
boolean add = true; //boolean to add new contact
boolean phoneValid; //boolean to validate phone number
Scanner scan = new Scanner(System.in);
ArrayList < Contact > PhoneBook = new ArrayList < > ();
while (add) {
phoneValid = false;
System.out.println("Type (N) to add a new contact, (D) to display your phonebook, or (Q) to quit!");
input = scan.nextLine();
if (input.equalsIgnoreCase("N")) {
System.out.println("Enter the contact's first name: ");
first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
last = scan.nextLine();
while (!phoneValid) {
System.out.println("Enter the contact's phone number: XXX-XXX-XXXX");
phone = scan.nextLine();
if (phone.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) {
phoneValid = true;
break;
} else {
System.out.println("Sorry, I didn't catch that!");
}
}
Contact contact = new Contact(first, last, phone);
PhoneBook.add(contact);
} else if (input.equalsIgnoreCase("Q")) {
add = false;
System.out.println("Goodbye!");
break;
} else if (input.equalsIgnoreCase("D")) {
for (Contact c: PhoneBook) {
System.out.println(c);
}
} else {
System.out.println("Sorry, I didn't catch that!");
}
}
} //end main
} //end Class ComputerDriver

It sounds like you need to create some Getters. Most IDE's will do this for you.
For example, in your contact class add this:
public String getFirst(){ return first; }
Then do that for all of the items you want. When you want to print them out, set up a for each loop in your driver class like this:
for(Contact contact : PhoneBook){
System.out.println("Contact details: " + contact.getFirst() + " " + contact.getLast() + ", Phone #: " + contact.getPhoneNumber());
}
Alternatively, you could also create a method in you contacts class that takes the println contents from above and spits it out. For example:
public void printContactDetails(){ System.out.println("...");}
then in your for each loop call: contact.printContactDetails();

Related

how to add bunch of data into linked list

Basically, I just tried to learn linked lists but I can't seem to understand how to insert a bunch of data from different variables into it. Does it work as an array/ ArrayList? Before we end the loop we are supposed to store the data right, but how??
Let say I have variables ( name, age, phonenum).
'''
char stop='Y';
while(stop!='N'){
System.out.println("\nEnter your name : ");
int name= input.nextLine();
System.out.println("\nEnter your age: ");
int age= input.nextInt();
System.out.println("\nEnter your phone number: ");
int phonenum= input.nextLine();
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
stop = sc.nextLine().charAt(0);
}
'''
First, change your code to use appropriate types. Name and phone should be of type String, not int.
Define a class to hold your fields. Records are an easy way to do that.
record Person ( String name , int age , String phone ) {}
Declare your list to hold objects of that class.
List< Person > list = new LinkedList<>() ;
Instantiate some Person objects, and add to list.
list.add( New Person( "Alice" , 29 , "477.555.1234" ) ) ;
In the line above, I hard-coded some example data. In your own code, you will be passing to the constructor the variables you populated by interacting with the user.
list.add( New Person( name , age , phonenum ) ) ;
You can create an object which has name, age and phenomenon then create an insert method which you call in your while loop.
In psuedo code it would look something like this:
public class Data {
String name;
int age;
int phenomenon;
//constructor
//getters & setters
}
This class above will hold contain the user input. You can gather all the user input and store it in an array and perform the insert with array of data instead of inserting one object at a time
public void InsertData(LinkedList<Data> list, Arraylist<Data> input) {
for(Data d: input){
list.add(d);
}
}
You can read up on linkedlists a bit more here to understand how exactly linkedlists work and implement your own from scratch: https://www.geeksforgeeks.org/implementing-a-linked-list-in-java-using-class/
Try this
Possibility : 1
import java.util.*;
public class Naddy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char stop = 'Y';
LinkedList<Object> list = new LinkedList<Object>();
while (stop != 'N') {
System.out.println("\nEnter your name : ");
String name = input.nextLine();
System.out.println("\nEnter your age: ");
int age = input.nextInt();
System.out.println("\nEnter your phone number: ");
long phonenum = input.nextLong();
list.add(name);
list.add(age);
list.add(phonenum);
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
input.nextLine();
stop = input.nextLine().charAt(0);
}
System.out.println(list);
}
}
possibility : 2
import java.util.*;
public class Naddy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char stop = 'Y';
LinkedList<User> list = new LinkedList<User>();
while (stop != 'N') {
System.out.println("\nEnter your name : ");
String name = input.nextLine();
System.out.println("\nEnter your age: ");
int age = input.nextInt();
System.out.println("\nEnter your phone number: ");
long phonenum = input.nextLong();
list.add(new User(name, age, phonenum));
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
input.nextLine();
stop = input.nextLine().charAt(0);
}
System.out.println(list);
}
}
class User {
private String name;
private int age;
private long phonenum;
public User() {
}
public User(String name, int age, long phonenum) {
this.name = name;
this.age = age;
this.phonenum = phonenum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getPhonenum() {
return phonenum;
}
public void setPhonenum(long phonenum) {
this.phonenum = phonenum;
}
#Override
public String toString() {
return "User [age=" + age + ", name=" + name + ", phonenum=" + phonenum + "]";
}
}

Collections.sort() error occuring while sorting ArrayList [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to sort by name ArrayList elements but I couldn't solve problem . . . . . .
Could someone help?
ERROR At case 4: Collections.sort(contact);
ERROR "Required type: List Provided: List reason: no
instance(s) of type variable(s) T exist so that Data conforms to
Comparable<? super T>"
below code works fine without sort
public class AddressBook {
private static List<Data> contact = new ArrayList<Data>();
public static void main(String[] args) {
AddressBook addressBook = new AddressBook();
Scanner sc = new Scanner(System.in);
int menu;
String choice;
String choice2;
System.out.println(" =========================== ");
System.out.println(" | 0. Exit. |");
System.out.println(" | 1. Add contact. |");
System.out.println(" =========================== ");
try
{
menu = sc.nextInt();
while (menu != 0) {
switch (menu) {
case 1:
while (menu != 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 Phone: ");
String homePhone = sc.next();
if (homePhone.length()!=11 || !homePhone.startsWith("8")) {
System.out.println("Number should start with '8' and has '11' digit" );
}else {
System.out.println("Enter Email: ");
String personalWebSite = sc.next();
contact.add(new Data(firstName, lastName,
homePhone, personalWebSite));
}
System.out
.println("Would you like to add someone else? 1: Yes, 2: No");
menu = sc.nextInt();
}
break;
case 2:
System.out
.println("Enter First Name of contact that you would like to edit: ");
choice = sc.next();
addressBook.deleteByFirstName(choice);
System.out.println("Enter First Name: ");
String firstName = sc.next().toUpperCase();
System.out.println("Enter Last Name: ");
String lastName = sc.next();
System.out.println("Enter Phone: ");
String homePhone = sc.next();
System.out.println("Enter Email: ");
String personalWebSite = sc.next();
contact.add(new Data(firstName, lastName,
homePhone, personalWebSite));
break;
case 3:
System.out.println("------------------");
System.out.println("1. Search number: ");
System.out.println("2. Search name: ");
System.out.println("------------------");
int search= sc.nextInt();
if(search==1) {
System.out
.println("Enter Number of contact: ");
choice2 = sc.next();
addressBook.searchByPhoneNumber(choice2);
break;
}else {
System.out
.println("Enter First Name of contact: ");
choice = sc.next();
addressBook.searchByFirstName(choice);
break;
}
case 4:
Collections.sort(contact);
//ERROR occurring here
case 5:
System.out.println("This is a list of every contact");
System.out.println(addressBook.contact);
break;
case 6:
System.out.println("------------------");
System.out.println("1. Delete by name: ");
System.out.println("2. Delete all: ");
System.out.println("------------------");
int del= sc.nextInt();
if(del==1){
System.out
.println("Enter First Name of contact that you would like to delete: ");
choice = sc.next();
addressBook.deleteByFirstName(choice);
break;
}else{
System.out.println("Successfully Deleted");
System.out.println("");
contact.clear();
}
break;
default:
throw new IllegalStateException("Unexpected value: " + menu);
}
System.out.println(" =========================== ");
System.out.println(" | 0. Exit. |");
System.out.println(" | 1. Add contact. |");
System.out.println(" =========================== ");
menu = sc.nextInt();
}
}
catch(InputMismatchException exception)
{
System.out.println("This is not an integer");
}
System.out.println("Good-Bye!");
}
private void searchByFirstName(String firstName) {
for (Iterator<Data> iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getFirstName().equalsIgnoreCase(firstName)) {
System.out.println(temp);
return;
}
}
System.out.println("No contact with first name " + firstName
+ " was found.");
}
private void searchByPhoneNumber(String homePhone) {
for (Iterator<Data> iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getHomePhone().equalsIgnoreCase(homePhone)) {
System.out.println(temp);
return;
}
}
System.out.println("No contact with number " + homePhone
+ " was found.");
}
private void deleteByFirstName(String firstName) {
for (Iterator<Data> iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getFirstName().equalsIgnoreCase(firstName)) {
iterator.remove();
return;
}
}
System.out.println("No contact with first name " + firstName
+ " was found.");
}
private void deleteAll(String all) {
for (Iterator<Data> iterator = contact.iterator(); iterator.hasNext();) {
iterator.remove();
return;
}
System.out.println("Deleting...");
}
private static int[] selectionSortAlg(int[] a, int n) {
for (int i = 0; i < n - 1; i++) {
int iMin = i;
for (int j = i + 1; j < n; j++) {
if (a[j] < a[iMin]) {
iMin = j; // index of smallest element
}
}
int temp = a[i];
a[i] = a[iMin];
a[iMin] = temp;
System.out.println("Pass..." + i + "..." + Arrays.toString(a));
}
return a;
}
public static class Data {
private String firstName = null;
private String lastName = null;
private String homePhone = null;
private String personalWebSite = null;
public Data(String firstName,String lastName, String homePhone, String personalWebSite) {
this.firstName = firstName;
this.lastName = lastName;
this.homePhone = homePhone;
this.personalWebSite = personalWebSite;
}
public String getFirstName() {
return firstName;
}
public String getHomePhone() {
return homePhone;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String toString() {
return String.format(firstName+" "+lastName+" "+homePhone+" "+personalWebSite);
}
}
}
class T {
private String firstName = null;
private String lastName = null;
private String homePhone = null;
private String personalWebSite = null;
public T(String firstName,String lastName, String homePhone, String personalWebSite) {
this.firstName = firstName;
this.lastName = lastName;
this.homePhone = homePhone;
this.personalWebSite = personalWebSite;
}
public String getFirstName() {
return firstName;
}
public String getHomePhone() {
return homePhone;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String toString() {
return String.format(firstName+" "+lastName+" "+homePhone+" "+personalWebSite);
}
}
I am not quite sure, but I think you need to do this(in your case 4):
Collections.sort(contact, new Comparator<Data>() {
#Override
public int compare(Data contact1, Data contact2) {
return contact1.getFirstName().compareTo(contact2.getFirstName());
}
});
Give it a try, I had used it somewhere else, and it worked. Hope it helps. Cheers :)
Use in this way
contact.sort( Comparator.comparing(Data::getFirstName) );
You have 2 options whether implement Comparable or provide comparator to sorting function, i.e.
Collections.sort(contact, (d1,d2) -> d1.firstName.compareTo(d2.firstName));
or
contact.sort((d1,d2) -> d1.firstName.compareTo(d2.firstName));
Your class Data you implement comparable, look at here:
https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/
public static class Data implements Comparable<Data>
...
public int compareTo(Data m) {
...
}
Either pass a comparator in sort method or make Data class implement Comparable interface and implement compareTo()
#GiorgosDev gave an example in which data class is expected to implement comparable interface.
Either implement comparable in Data class or pass comparator in sort method. Example Collections.sort(contact, Comparator.comparing(Data::getFirstName));

ArrayLists (Removing and Changing Elements)

Hello everyone I am an amateur in Java and had some specific questions about a program using ArrayLists. The program is made up of several classes, and its purpose is to add, change, remove, and display friends from a Phone Book. I have the add and display methods done, but I'm having trouble with the remove and change method. I saw a similar case on this site, but it did not help me solve my problems. Any help at all would be much appreciated. This is what I have so far:
package bestfriends;
import java.util.Scanner;
import java.util.ArrayList;
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
{
if(firstName.equalsIgnoreCase(myBFFs.get(i).getFirstName()) && lastName.equalsIgnoreCase(myBFFs.get(i).getLastName()))
{
found = true;
}
else
i++;
}
}
}
That was my Helper Class, for which I'm having trouble with the removeABFF method, and still need to create a changeABFF method from scratch. Next is my main class:
package bestfriends;
import java.util.Scanner;
public class BFFPhoneBook
{
public static void main(String args[])
{
int menuOption = 0;
Scanner keyboard = new Scanner(System.in);
BFFHelper myHelper = new BFFHelper();
do
{
System.out.println("1. Add a Friend");
System.out.println("2. Change a Friend");
System.out.println("3. Remove a Friend");
System.out.println("4. Display a Friend");
System.out.println("5. Exit");
System.out.print("Enter your selection: ");
menuOption = keyboard.nextInt();
switch (menuOption)
{
case 1:
myHelper.addABFF();
break;
case 2:
myHelper.changeABFF();
break;
case 3:
myHelper.removeABFF();
break;
case 4:
myHelper.displayABFF();
break;
case 5:
break;
default:
System.out.println("Invalid option. Enter 1 - 5");
}
} while (menuOption != 5);
}
}
This is my last class:
package bestfriends;
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
// friendIdNumber = friendNumber++;
}
public boolean equals(Object aFriend)
{
if (aFriend instanceof BestFriends )
{
BestFriends myFriend = (BestFriends) aFriend;
if (lastName.equals(myFriend.lastName) && firstName.equals(myFriend.firstName))
return true;
else
return false;
}
else
return false;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
To explore and manipulate a arraylist an iterator is used
the object lacks the Setters
declare variables
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
BestFriends best;
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
best= new BestFriends();
}
Delete
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
String name= keyboard.next().toLowerCase();// entry name to be removed
Iterator<BestFriends> nameIter = myBFFs.iterator(); //manipulate ArrayList
while (nameIter.hasNext()){
best = nameIter.next(); // obtained object list
if (best.getNickName().trim().toLowerCase().equals(name)){ // if equals name
nameIter.remove(best); // remove to arraylist
}
}
}
Update
public void changeABFF()
{
System.out.print("Enter a friend's name to be change: ");
String name= keyboard.next().toLowerCase().trim();//entry name to be update
Iterator<BestFriends> nameIter = myBFFs.iterator();
while (nameIter.hasNext()){
best = nameIter.next();
if (best.getNickName().trim().toLowerCase().equals(name)){// if equals name
best.setNickName("NEW DATE");//update data with new data Setters
....
}
}
}
In your remove method you do not accept any input of the values
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
....
As you are using firstNamer and lastName to find the object you needs these values
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();

Java Address Book String Reading

I have been having trouble with my removeContact method in the AddressBook class. I can get it to work when I enter a first name, but for some reason can't get it to work for the full name. This is probably simple but i'm just getting nowhere. Thanks
AddessBook Class
public class AddressBook {
private Contact contacts[] = new Contact[100]; //Array to hold all the contacts
private int count = 0; //Number of contacts in the array(in address book)
private String fileName;
AddressBook(String fileName){
this.fileName = fileName;
}
//Add Contact
public boolean addContact(Contact contact){
if(count<100){
contacts[count] = contact;
count++;
return true;
}else{
return false;
}
}
//Remove Contact
public boolean removeContact(String fullname){
for(int i = 0; i<count; i++){
if(fullname.equals(contacts[i].getFullName())){
for(int j = i; j<count; j++){
contacts[j] = contacts[j+1];
}
count--;
}else{
return false;
}
}
return true;
}
//Search Contact
//Display Contacts
public void displayContacts(){
for(int i = 0; i<count; i++){
System.out.println(contacts[i]);
}
}
}
Contact Class
public class Contact {
private String firstName;
private String lastName;
private String phone;
//Contact constructor
Contact(String firstName, String lastName, String phone){
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
}
//First name getter
public String getFirstName(){
return firstName;
}
//Last name getter
public String getLastName(){
return lastName;
}
//Full name getter
public String getFullName(){
return firstName+" "+lastName;
}
//Phone number getter
public String getPhone(){
return phone;
}
//First name mutator
public void setFirstName(String firstName){
this.firstName = firstName;
}
//Last name mutator
public void setLastName(String lastName){
this.lastName = lastName;
}
//Phone number mutator
public void setPhone(String phone){
this.phone = phone;
}
//Method to compare first and last names for similarity
public boolean compare(Object o){
Contact contact = (Contact) o;
if(firstName == contact.firstName && lastName == contact.lastName){
return false;
}else{
return true;
}
}
public String toString(){
return firstName+" "+lastName+" "+phone;
}
}
Main Class
import java.util.*;
public class Main {
public static void main(String [] args){
AddressBook addressbook = new AddressBook("Info.txt");
Scanner s = new Scanner(System.in);
boolean quit = false;
while(!quit){
System.out.println("What would you like to do?");
System.out.println(" 1) Display all contacts");
System.out.println(" 2) Add a contact");
System.out.println(" 3) Remove a contact");
System.out.println(" 4) Search a contact");
System.out.println(" 5) Exit");
switch(s.nextInt()){
case 1:
addressbook.displayContacts();
break;
case 2:
System.out.println("First Name: ");
String fName = s.next();
System.out.println("Last Name: ");
String lName = s.next();
System.out.println("Phone Number: ");
String pNumber = s.next();
addressbook.addContact(new Contact(fName, lName, pNumber));
break;
case 3:
System.out.println("Enter in full name: ");
String fullname = s.next();
addressbook.removeContact(fullname);
break;
case 4:
System.out.println("Enter the name of the contact you are looking for: ");
case 5:
quit = true;
break;
}}}}
You are asking for the full name and then comparing it only with the first name:
if(fullname.equals(contacts[i].getFirstName())){
Just compare it with the full name...
When you make your call to the "removeContact" method, you are passing as parameter only the name, not the last name; let say you create the contact "John Doe". When you search for "John Doe" you pass "John" as the name to the method but "Doe" is the next token in the scanner, so when you try to do s.nextInt() you have a problem because "Doe" is not an int.
Also, your removeContact method is not gonna work when you have more than 1 contact. You are doing a return if the first contact of the address book is not the one you are looking for.
Edit:
Try this and let me know what happens:
case 3:
System.out.println("Enter in full name: ");
String firstName = s.next();
String lastName = s.next();
addressbook.removeContact(firstName + " " + lastName);
break;
Edit 2:
// Remove Contact
public boolean removeContact(String fullname) {
for (int i = 0; i < count; i++) {
// No need for an else here
if (fullname.equals(contacts[i].getFullName())) {
for (int j = i; j < count; j++) {
contacts[j] = contacts[j + 1];
}
count--;
return true;
}
}
return false;
}
Ok, I ran your code and tried to remove a name , so I got this error :
Exception in thread "main" java.util.InputMismatchException
Your remove method is not correct. You can easily have 17 Bob's in your Address Book - "Bob Smith", "Bob Jacobs", "Bob Ahmed" , whatever...
You need to fix the removeContact method to look more like this :
public boolean removeContact(String fname, String lname){
for(int i = 0; i<count; i++){
if(contacts[i].getFirstName().equals(fname) && contacts[i].getLastName().equals(lname)){
for(int j = i; j<count; j++){
contacts[j] = contacts[j+1];
}
Also, the case 3 of Main should lok like this :
case 3:
System.out.println("Enter in first name: ");
String firstname = s.next();
System.out.println("Enter in last name: ");
String lastname = s.next();
addressbook.removeContact(firstname, lastname);
break;

AddressBook Program Remove And Search Method Null Pointer Exceptions

EDIT5:My remove() method asks for a name to remove, and no matter what name I enter in it will delete the latest name in the array. I'm not sure how to fix this, and my search array will ask for a name and then declare a Null Pointer Exception error. The rest of my code is provided below.
case 3: //Remove a contact
System.out.print("Full name to remove: ");
Scanner rs = new Scanner(System.in);
String deleteName = rs.nextLine();
a1.remove(deleteName);
break;
case 4: //search a contact
System.out.print("Full name to search: ");
Scanner ss = new Scanner(System.in);
String searchName = ss.nextLine();
a1.search(searchName);
break;
EDIT4: Figured out the initialization problem.. can't believe I missed something so simple. My program now works nearly perfect, besides for my remove function, which encounters a null Pointer exception. Can someone explain to me why this happens? Also I've updated the code
EDIT3: I now have nothing yelling at me in my Contact and AddressBook classes. I just need to know how to make my methods in main work. As someone pointed out in the comments I need to initialize my methods and classes. Can someone please tell me where I need to put my constructor so these methods will work? I have them placed in multiple areas of my program already to no avail.
I'm working on an AddressBook program for my java class. I've constructed everything, but my methods in other classes are giving me some difficulty(I made all my methods public and my class specific variables private). Also I would like some feedback on how I constructed my methods. I was given a rough outline of what methods to use here:
Contact
-firstName:String
-lastName:String
-phone:String
+Contact(firstName:String,lastName:String, phone:String)
+getFullName():String
+getLastName():String
+getPhone():String
+setFirstName(firstName:String):void
+setLastName(lastName:String):void
+setPhone(phone:String):void
+equals(o:Object):boolean #currently not sure how to do this method
+toString():String
AddressBook class
-contacts:Contact[]
- count:int;
-fileName:String
+AddressBook(fileName:String)
+add(Contact c):boolean
+remove(fullName:String):boolean
+search(fullName:String):Contact
+display():void
+load():boolean
+save():boolean
+search(String fullName):boolean
Here is my code:
Contact class code:
public class Contact {
private String firstName;
private String lastName;
private String phone;
public Contact(String firstName, String lastName, String phone) {
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
}
public String getFullName(){
return firstName + " " + lastName;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public String getPhone(){
return phone;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setPhone(String phone){
this.phone = phone;
}
/*public boolean equals(Contact o){ //not sure how to use this method, tips/suggestions?
}*/
public String toString(){
return firstName + ":" + lastName + ":" + phone;
}
}
AddressBook Class
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class AddressBook {
private Contact[] contacts = new Contact[100];
private int count = 0;
private String fileName;
public AddressBook(String fileName) {
this.fileName = fileName;
}
public boolean add(Contact c) {
// Checks to see if the array is full
if (count > 99) {
return false;
}
// Adds the new contact into the array
contacts[count] = c;
// increment count
count++;
return true;
}
public boolean remove(String deleteName) { //switched fullName to deleteName to avoid duplicate variable problems
for (int i = 0; i < count; i++) {
if(contacts[i].getFullName() == deleteName) {
contacts[i] = null;
contacts[i] = contacts[i-1];
}
}
count--;
return true;
}
public Contact search(String searchName){ //switched fullName to searchName to avoid duplicate variable problems in the main class
for(int i = 0; i < contacts.length; i++){
if (contacts[i].getFullName() == searchName) {
return contacts[i];
}
} return null;
}
public void display() {
System.out.println("Name Phone Number"); //setting up the format for displaying contacts
System.out.println("-------------------------------");
for (int i = 0; i < count; i++) { //for loop printing out and displaying contacts
System.out.println(contacts[i].getFirstName() + " "
+ contacts[i].getLastName() + "\t\t"
+ contacts[i].getPhone());
}
System.out.println("-------------------------------");
}
public boolean load() {
//reads the file address.txt and loads it
try {
File fr = new File(fileName);
Scanner s = new Scanner(fr);
while(s.hasNextLine()) {
String oStore = s.nextLine(); //Storing the line of string here so it can be split
String[] aStore = oStore.split(":"); //Splits oStore up and inputs the values into constructor
contacts[count]=new Contact(aStore[0], aStore[1], aStore[2]);
count++;//increments count each contact
}
s.close();
return true;
} catch (Exception e){
return false;
}
}
public boolean save() {
// Writes the new contact into the file address.txt
try {
FileWriter fw = new FileWriter(fileName);
for (int i = 0; i < contacts.length; i++) {
fw.write(contacts[i].getFirstName() + ":"
+ contacts[i].getLastName() + ":"
+ contacts[i].getPhone() + "\n");
}
fw.close();
} catch (Exception e) {
return false;
}
return true;
}
/*public boolean search(String searchName) { //switched fullName to searchName to avoid duplicate variable problems in the main class
for(int i = 0; i <contacts.length; i++){
if (contacts[i].getFullName() == searchName) {
return contacts[i].getFullName() + contacts[i].getPhone();
}
}
return true;
}*/
}
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
AddressBook a1 = new AddressBook("address.txt");
boolean pQuit = false; //boolean value to end the program
a1.load();
System.out.println("Welcome. Address book is loaded.");
System.out.println("");
do{
//Setting up the initial menu
System.out.println("What would you like to do?");
System.out.println("1) Display all contacts");
System.out.println("2) Add a contact");
System.out.println("3) Remove a contact");
System.out.println("4) Search a contact");
System.out.println("5) Exit");
System.out.println("Your choice: ");
Scanner s = new Scanner(System.in); //Scanner for user's choice
int choice = s.nextInt(); //User picks menu choice
System.out.println("\n");//line break
switch(choice){
case 1: //Display all contacts
a1.display();
break;
case 2: //Add a contact
System.out.print("First name:");
String firstName = s.next(); //Stores first name in firstName
System.out.print("Last name:");
String lastName = s.next(); //Stores last name in lastName
System.out.print("Phone number:");
String phone = s.next();
a1.add(new Contact(firstName,lastName,phone));
System.out.println("Contact added.");
break;
case 3: //Remove a contact
System.out.print("Full name to remove: ");
Scanner rs = new Scanner(System.in);
String deleteName = rs.nextLine();
a1.remove(deleteName);
break;
case 4: //search a contact
System.out.print("Full name to search: ");
Scanner ss = new Scanner(System.in);
String searchName = ss.nextLine();
a1.search(searchName);
break;
case 5: //exit the program
a1.save();
System.out.println("Addres book is saved to file.");
pQuit = true;
break;
default:
System.out.println("That is not a valid input.");
}
}while (pQuit == false);
}
}
Right now in my main method none of the methods I have called work because they are undefined. Same instance happened when I tried to use the contacts array in my +equals(o:Object):boolean method. All help is much appreciated, and if you see anything wrong in my methods or anything at all I could fix and improve please let me know!
Thanks in advance for the help.
EDIT1: Also please note the two search methods I was given. I pretty much constructed the same code for both. Eclipse right now is yelling at me telling me to change the name of the methods. I would like to know if I constructed the methods incorrectly, or why I would be given two of the same named methods to use in my program.
EDIT2: Updated to my new code. Changed a couple things, methods still do not work though.

Categories