ArrayLists (Removing and Changing Elements) - java

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();

Related

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));

HashMap returning null after adding values

I know this question has been asked before but I can't understand how to fix this issue. I'm adding values to a HashMap and in setStudent and then when I try to change the value in replaceName but the key doesn't seem to exist.
import java.util.*;
public class Student {
private HashMap<String, List<String>> studentDetails = new HashMap<String, List<String>>();
private HashMap<String, List<String>> studentModules = new HashMap<String, List<String>>();
public void setStudent(String id, String name, String postalAddress, String emailAddress, String degreeTitle, String dateEnrolled, List<String> modules) {
List<String> information = new ArrayList<>();
information.add(name);
information.add(postalAddress);
information.add(emailAddress);
information.add(degreeTitle);
information.add(dateEnrolled);
studentDetails.put(id, information);
studentModules.put(id, modules);
}
public List<String> getStudentDetails(String x) {
return studentDetails.get(x);
}
public List<String> getStudentModules(String x) {
return studentModules.get(x);
}
public void replaceName(String id, String name, String postalAddress, String emailAddress, String degreeTitle, String dateEnrolled) {
List<String> information = new ArrayList<>();
information.add(name);
information.add(postalAddress);
information.add(emailAddress);
information.add(degreeTitle);
information.add(dateEnrolled);
studentDetails.replace(id, information);
}
}
My main class is quite long but basically it takes user input to get the values:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner source = new Scanner(System.in);
RecordManager r = new RecordManager();
Module m = new Module();
Student s = new Student();
ChangeName c = new ChangeName();
while (true) {
System.out.println("Please enter the student id:");
r.setId(source.nextLine());
System.out.println("Please enter the student name:");
r.setName(source.nextLine());
System.out.println("Please enter the student address:");
r.setAddress(source.nextLine());
System.out.println("Please enter the student email address:");
r.setEmailAddress(source.nextLine());
System.out.println("Please enter the degree title:");
r.setDegreeTitle(source.nextLine());
System.out.println("Please enter the date enrolled:");
r.setDateEnrolled(source.nextLine());
List<String> a = new ArrayList<>();
while (true) {
System.out.println("Please enter the module name:");
String name = source.nextLine();
m.setName(name);
a = r.addModule(name, a);
m.setTitle(name);
System.out.println("Please enter the module code:");
m.setCode(source.nextLine());
while (true) {
System.out.println("Please enter the module mark (between 1 and 100):");
int mark = source.nextInt();
if (mark > 0 && mark <101) {
m.setMark(mark);
break;
}
else {
System.out.println("Module mark must be between 1 and 100");
}
}
System.out.println("Please enter the module credits:");
m.setCredits(source.nextInt());
m.setModule();
System.out.println("Would you like to enter another module? (Y/N)");
String more = source.next();
if (more.equalsIgnoreCase("N")) {
break;
}
source.nextLine();
}
r.setModules(a);
s.setStudent(r.getId(), r.getName(), r.getAddress(), r.getEmailAddress(), r.getDegreeTitle(), r.getDateEnrolled(), r.getModules());
r.addStudents(r.getId(), s.getStudentDetails(r.getId()));
System.out.println("Would you like to enter the details for another student? (Y/N)");
String another = source.next();
if (another.equalsIgnoreCase("N")) {
break;
}
source.nextLine();
}
while (true) {
System.out.println("Full list of students and details (1) \nLookup a student by name (2) \nChange student name (3)");
source.nextLine();
int choice = source.nextInt();
if (choice == 1) {
for (String id : r.getStudents().keySet()) {
System.out.println(s.getStudentDetails(id) + " " + s.getStudentModules(id));
}
break;
}
else if (choice == 2) {
System.out.println("Please enter the full name of the student:");
source.nextLine();
String name = source.nextLine();
boolean exists = false;
int i = 0;
for (String id : r.getStudents().keySet()) {
if (s.getStudentDetails(id).get(i).equalsIgnoreCase(name)) {
System.out.println(s.getStudentDetails(id) + " " + s.getStudentModules(id));
exists = true;
}
i += 1;
}
if (exists == false) {
System.out.println("Student not found");
}
break;
}
else if (choice == 3) {
System.out.println("Please enter the ID of the student:");
source.nextLine();
String id = source.nextLine();
System.out.println("Please enter the new name:");
String name = source.nextLine();
c.changeName(id, name, s.getStudentDetails(id));
System.out.println(s.getStudentDetails(id));
break;
}
else {
System.out.println("Incorrect selection. Please enter 1, 2 or 3");
}
}
}
}
And finally I have the class to change the name:
import java.util.*;
public class ChangeName {
RecordManager r = new RecordManager();
Student s = new Student();
public void changeName(String id, String newName, List<String> details) {
s.replaceName(id, newName, details.get(1), details.get(2), details.get(3), details.get(4));
}
}
Any help would be greatly appreciated!!

display an entire arraylist in 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();

How to remove objects from ArrayLists

So i have this homework, to create a java movie program. It should have the add movie (title, actor and date of appearance), show (all the movies added) and remove movie(by movie title) options.
Up till now i was able to create the addMovie(), and showMovie() methods...but i got really stuck ad removeMovies().
Here is the code for the Main.java:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
static ArrayList<Movies> movHolder = new ArrayList<Movies>();
public static void main(String[] args) {
int op = -1;
while (op != 0){
op= menuOption();
switch(op){
case 1:
addMovies();
break;
case 2:
removeMovies();
break;
case 3:
showMovies();
break;
case 0:
System.out.print("\n\nYou have exited the program!");
break;
default:
System.out.println("\nWrong input!");
}
}
}
public static int menuOption(){
int option;
System.out.println("\nMenu\n");
System.out.println("1. Add new movies");
System.out.println("2. Remove movies");
System.out.println("3. Show all movies");
System.out.println("0. Exit program");
System.out.print("\nChoose an option: ");
option = input.nextInt();
return option;
}
public static void addMovies(){
String t, a, d;
input.nextLine();
System.out.println("\n---Adding movies---\n");
System.out.print("Enter title of movie: ");
t = input.nextLine();
System.out.print("Enter actor's name: ");
a = input.nextLine();
System.out.print("Enter date of apearance: ");
d = input.nextLine();
Movies mov = new Movies(t, a, d);
movHolder.add(mov);
}
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
}
public static void showMovies(){
System.out.print("---Showing movie list---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
}
}
And here is the Movies.java with the Movie class:
public class Movies {
private String title;
private String actor;
private String date;
public Movies (String t, String a, String d){
title = t;
actor = a;
date = d;
}
public Movies(){
title = "";
actor = "";
date = "";
}
public String getTitle(){
return title;
}
public String getActor(){
return actor;
}
public String getDate(){
return date;
}
public String toString(){
return "\nTitle: " + title +
"\nActor: " + actor +
"\nRelease date: " + date;
}
}
As you could probably see, i am a very beginner java programmer.
Please, if there is anyway someone could help with the removeMovie() method, i would be very grateful.
Since you have the index of the movie that should be removed (choice - 1) you can use ArrayList.remove(int)
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
movHolder.remove(choice-1);
You can use the remove(int index) method:
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
// Decrement the index because you're asking the user for a 1 based input.
movHolder.remove(choice - 1)
}
}

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