How to remove an object from an ArrayList<Class>? - java

I'm trying to remove the object from an ArrayList of
type Contact class. I am trying to take input from users and want to
delete that object from ArrayList
public class Contacts {
private String name, phoneNumber;
public Contacts(){
}
public Contacts(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
#Override
public String toString() {
return "Contacts{" +
"name='" + name + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
'}';
}
public static Contacts createContact(String name, String phoneNumber) {
return new Contacts(name, phoneNumber);
}
}
Here I tried to add objects with names and numbers and then print them and I want to delete a particular object.
public class Mobile {
ArrayList<Contacts> mycontacts;
public Mobile() {
this.mycontacts = new ArrayList<Contacts>();
}
public void addContacts() {
System.out.println("enter contact name");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println("enter contact number");
String number = sc.nextLine();
Contacts contacts = new Contacts(name, number);
mycontacts.add(contacts);
}
public void print() {
for (Contacts contacts : mycontacts) {
System.out.println(contacts.getName() + "->" + contacts.getPhoneNumber());
}
}
public String findcontact() {
Scanner scanner = new Scanner(System.in);
System.out.println("enter contact name");
String name = scanner.nextLine();
System.out.println("enter phone number");
String number = scanner.nextLine();
Contacts contacts = new Contacts(name, number);
int x = mycontacts.indexOf(contacts);
return mycontacts.get(x).getName();
}
public void remove() {
Scanner scanner = new Scanner(System.in);
System.out.println("enter contact name");
String name = scanner.nextLine();
System.out.println("enter contact number");
String number = scanner.nextLine();
Contacts contacts = new Contacts(name, number);
Iterator<Contacts> itr = mycontacts.iterator();
while (itr.hasNext()){
Contacts contacts1 = itr.next();
System.out.println(contacts1);
if (contacts1==contacts){
itr.remove();
}
}
}
}

You need to implement the equals method on your Contacts class, something like this
public boolean equals(Object other){
if(other instanceof Contract){
Contract otherC = (Contract)other;
return this.name.equals(otherC.name) && this.phoneNumber.equals(otherC.phoneNumber);
}
return false;
}

Java isn't my strong suit, but I think you can fix it like this:
Iterator<Contacts> itr = mycontacts.iterator();
while (itr.hasNext()){
Contacts contacts1 = itr.next();
System.out.println(contacts1);
if (contacts1.getName()==contacts.getName() && contacts1.getPhoneNumber() == contacts.getPhoneNumber()){
itr.remove();
}
}
Or simplified:
mycontacts.removeIf(i -> i.getName()==contacts.getName() && i.getPhoneNumber()==contacts.getPhoneNumber());
I think what is happening is that in this comparison: if (contacts1==contacts)
These will never be equal, as they are different objects, but they have the same values for their class variables.
https://www.baeldung.com/java-comparing-objects
the value of those objects is not 1. Rather it is their memory addresses in the stack that are different since both objects were created using the new operator.
edit: actually, another answer showed up while I was answering, which is better. I'll leave mine up since I think I gave more explanation.

There are two ways to remove an element from an ArrayList:
remove(Object object)
remove(int index)
So if you're using the name as the key, it could look something like:
public void removeContact(String name) {
for(contact : mycontacts) {
if(contact.name == name) {
mycontacts.remove(contact)
}
}
}

I tried using the following code, it worked. Thank you all who helped me. :)
for (Contacts mycontact : mycontacts) {
if (mycontact.getName().equals(name)) {
System.out.println("removed contact"+mycontact.getName()+"->"+mycontact.getPhoneNumber());
mycontacts.remove(mycontact);
}
else{
System.out.println("error deleting contact");
}
}

Related

Difficulty setting and updating objects in a Sorted ArrayList [duplicate]

This question already has answers here:
method in class cannot be applied to given types
(7 answers)
Closed 2 years ago.
I wish to be able to update information about objects entered by a user. I would like the user to enter a book name and user name to take out the book, as well as being able to return it with the same information. The objects have to be inserted into the right place in my sortedarraylists. Each user is assumed to be unique and each book can only be taken out by one user (who can take out up to 3 books).
When I try to compile my code, I get this error message:
java: method issueBook in class Driver cannot be applied to given types;
required: Book,User
found: no arguments
reason: actual and formal argument lists differ in length
This corresponds to issueBook(); in case i of my menu.
I also have User and Book classes that implement Comparable<Book> etc. I tried to omit as much irrelevant code as I could, such as the filereader to scan in new user and book objects. I included the book and user classes in case they need to be looked at (I think they are mostly fine). Please let me know if you need any more details however.
import java.io.*;
import java.util.Scanner;
public class Driver {
static Scanner sc = new Scanner(System.in);
private static void mainMenu() {
System.out.println("------------------------------\n"+
"f: Finish running the program\n" +
"b -Display on the screen the information about all the books in the library\n" +
"u -Display on the screen the information about all the users.\n" +
"i -Update the stored data when a book is issued to a user\n" +
"r -Update the stored data when a user returns a book to the library\n" +
"------------------------------\n" +
"Type a letter and press Enter\n");
}
private static User readNames() throws User.InvalidBookLimitException {
System.out.println("Enter the user's firstname: ");
String firstName = sc.next();
System.out.println("Enter the user's surname: ");
String surName = sc.next();
sc.nextLine(); //TODO check this
return new User(firstName, surName, 0);
}
private static User readUserData(User user) throws User.InvalidBookLimitException {
User u = readNames();
System.out.println("Enter " + user + "'s age, and press Enter");
int numberOfBooks = sc.nextInt();
sc.nextLine();
return new User(u.getFirstName(), u.getSurName(),u.getNumberOfBooks());
}
private static Book readBookName (){
System.out.println("Type in the name of the book");
String bookName = sc.nextLine();
return new Book(bookName);
}
/* public SortedArrayList<User> sortedUsers = new SortedArrayList<>(); public SortedArrayList<Book> sortedBooks = new SortedArrayList<>();*/
//If this part is commented out, I get errors since I can't seem to access the arraylists in the
// main method for the issueBook/returnBook methods.
public void issueBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)){
b.loanStatus(true);
/*b.setLoanerNames(user);*/ b.setLoanerNames("John", "Doe");
break;
}
}
for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()+1);
}
}
}
public void returnBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)){
b.loanStatus(false);
b.setLoanerNames(null, null);
break;
} for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()-1);
}
}
}
}
public static <E> void main(String[] args) throws FileNotFoundException, User.InvalidBookLimitException {
//These SortedArrayLists have been derived from the sorted arraylist class
SortedArrayList<User> sortedUsers = new SortedArrayList<>();
SortedArrayList<Book> sortedBooks = new SortedArrayList<>();
mainMenu(); //main menu printing method
char ch = sc.next().charAt(0);
sc.nextLine();
while (ch !='f') //the program ends as desired if f is pressed
{ switch(ch){
case 'b':
System.out.println("Displaying information about all books in the library: ");
/*for (Object item : sortedBooks) {
System.out.println(sortedBooks.toString());
}*/
System.out.println(sortedBooks/*.toString()*/);
break;
case 'u':
System.out.println("Displaying information about all users");
System.out.println(sortedUsers/*.toString()*/);
break;
case 'i':
System.out.println("Enter the loaning out data. ");
System.out.println("Enter the user's first name and surname: ");
readNames();
System.out.println("Enter the name of the book: ");
readBookName();
issueBook();
or maybe if(u1.compareTo(u2) == 0)*/
break;
case 'r':
System.out.println("Please the details of the book to be returned: ");
/*Book b = new Book("test1", "test2", true, "lol","lol2");*/
//this was just a test and didn't work
/*returnBook(b);*/
break;
default:
System.out.println("Invalid input, please enter f, b, i or r");
}
mainMenu();
ch = sc.next().charAt(0);
sc.nextLine();
}
}
}
My sorted arraylist class with a (working) insert method:
import java.util.ArrayList;
public class SortedArrayList<E extends Comparable<E>> extends ArrayList<E> {
//no need for a generic in the insert method as this has been declared in the class
public void insert(E value) {
if (this.size() == 0) {
this.add(value);
return; }
for (int i = 0; i < this.size(); i++) {
int comparison = value.compareTo((E) this.get(i));
if (comparison < 0) {
this.add(i, value);
return; }
if (comparison == 0) {
return; }
}
this.add(value);
}
User class:
import java.io.PrintWriter;
public class User implements Comparable<User> {
private String firstName;
private String surName;
private int numberOfBooks;
public User(){
firstName = "";
surName = "";
numberOfBooks = 0;
}
public class InvalidBookLimitException extends Exception{
public InvalidBookLimitException(){
super("Invalid number of books");
}
}
public User(String name1, String name2, int books) throws InvalidBookLimitException {
this.firstName = name1;
this.surName = name2;
if (books>3) throw new InvalidBookLimitException ();
this.numberOfBooks = books;
}
public String getFirstName() {
return firstName;
}
public String getSurName(){
return surName;
}
public int getNumberOfBooks(){
return numberOfBooks;
}
public boolean borrowMoreBooks(){
return numberOfBooks < 3;
}
public void setNumberOfBooks(int numberOfBooks){
this.numberOfBooks=numberOfBooks;
}
public void setUser(String name1, String name2, int books){
firstName = name1;
surName = name2;
numberOfBooks = books;
}
public boolean userNameTest (User otherUser){
return (firstName.equals(otherUser.firstName) && surName.equals(otherUser.surName));
}
/* public boolean loanAnotherBook(){
return !(numberOfBooks<3);
numberOfBooks++;
}*/
public void printName(PrintWriter f){f.println(firstName+ " " + surName);}
/*
public void setUser(User user) {
if (loanStatus == false){
loanStatus = Driver.readNameInput();
loanStatus = true;
}
}*/
#Override
public String toString(){
return "Name: " + firstName + " " + surName + " | Number of books: " + numberOfBooks;
}
public int compareTo(User u) {
/* int snCmp = surName.compareTo(u.surName);
if (snCmp != 0)
return snCmp;
else{
int fnCmp = firstName.compareTo(u.firstName);
if (fnCmp !=0)
return fnCmp;
}*/
int fnCmp = firstName.compareTo(u.firstName);
if (fnCmp != 0) return fnCmp;
int snCmp= surName.compareTo(u.surName);
if (snCmp !=0) return snCmp;
else return numberOfBooks -u.numberOfBooks;
}
#Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
Book class:
public class Book implements Comparable<Book>{
public String bookName;
public String authorName;
public boolean loanStatus;
public String loanerFirstName;
public String loanerSurName;
//if boolean loanStatus == true private string loaner name
public Book(){
bookName = "";
authorName = "";
loanStatus = false;
loanerFirstName = null;
loanerSurName = null;
}
Book(String book, String author, boolean loanStatus, String loanerFirstName, String loanerSurName) {
this.bookName = book;
this.authorName = author;
this.loanStatus = loanStatus;
this.loanerFirstName = loanerFirstName;
this.loanerSurName = loanerSurName;
}
Book(String book){
this.bookName=book;
}
public String getBookName(){
return bookName;
}
public String getAuthorName(){
return bookName;
}
public boolean getLoanStatus(){
return loanStatus;
}
public String getLoanerFirstName(){
return loanerFirstName;
}
public String getLoanerSurName(){
return loanerSurName;
}
public void setBook(String book, String author, boolean loanStatus, String loanerFirstName, String loanerSurName){
bookName = book;
authorName = author;
loanStatus = loanStatus;
loanerFirstName = loanerFirstName;
loanerSurName = loanerSurName;
}
public void setBookName(String bookName){
this.bookName=bookName;
}
public void loanStatus(boolean loanStatus){
this.loanStatus=loanStatus;
}
public void setLoanerNames(String loanerFirstName, String loanerSurName){
this.loanerFirstName=loanerFirstName;
this.loanerSurName=loanerSurName;
}
/* public boolean nameTest (User otherUser){
return (loanerFirstName.equals(otherUser.loanerFirstName)&& loanerSurName.equals(otherUser.loanerSurName));
}
*/
public String toString(){
return "Book: " + bookName + " | Author: " + authorName + " | Loan status: " + loanStatus + " | Loaned to: " + loanerFirstName + " " + loanerSurName ;
}
//this may be redundant TODO
/* public void setLoanStatus(User user){
loanStatus = false;
}*/
//This compare method allows new user objects to be compared to ones in the
#Override //sortedArrayList, enabling the insertion method.
public int compareTo(Book b) {
int bnCmp = bookName.compareTo(b.bookName);
if (bnCmp != 0) return bnCmp;
int anCmp= authorName.compareTo(b.authorName);
if (anCmp !=0) return anCmp;
// int lsCmp= loanStatus.(b.loanStatus);
// if (lsCmp !=0) return lsCmp;
int lrfnCmp =loanerFirstName.compareTo(b.loanerFirstName);
if (lrfnCmp !=0) return lrfnCmp;
int lrlnCmp =loanerSurName.compareTo(b.loanerSurName);
if (lrlnCmp !=0) return lrlnCmp;
else return 0;
}
}
User user = readNames();
Book book = readBookName();
issueBook(book, user);
You have to pass the user and book which you have created while calling the issueBook method.

generating groups from txt file and generating them based on preferences

I am designing a group generator that takes in preferences such as “mix gender”, “mix nationality”... I am putting a list of student names, followed by nationality and gene set, in an arraylist. What is the easiest way to generate groups, based on user input, that each group consists of people from different nationalities, or balanced gender.
public ArrayList<String> readEachWord(String className)
{
ArrayList<String> readword = new ArrayList<String>();
Scanner sc2 = null;
try {
sc2 = new Scanner(new File(className + ".txt"));
} catch (FileNotFoundException e) {
System.out.println("error, didnt find file");
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.next();
readword.add(s);
}
}
return readword;
}
I am using this to read a text file, and on each line, I have each student's name nationality and gender. I put them into an ArrayList and am right now trying to figure out how to evenly distribute them based on the user-desired group numbers.
I am using a txt file to store all the information since this group generator is customized for my school.
You can use the groupinBy method
basic tutorial
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Scratch {
public static void main(String[] args) {
String student1 = "Macie American Female";
String student2 = "Yago Brazilian Male";
String student3 = "Tom American Male";
List<String> students = Arrays.asList(student1, student2, student3);
System.out.println(groupByGender(students));
System.out.println(groupByNationality(students));
}
private static Map<String, List<Student>> groupByNationality(List<String> students) {
return students.stream().map(s -> mapToStudent(s)).collect(Collectors.groupingBy(Student::getNationality));
}
private static Map<String, List<Student>> groupByGender(List<String> students) {
return students.stream().map(s -> mapToStudent(s)).collect(Collectors.groupingBy(Student::getGender));
}
private static Student mapToStudent(String s) {
String[] ss = s.split(" ");
Student student = new Student();
student.setName(ss[0]);
student.setNationality(ss[1]);
student.setGender(ss[2]);
return student;
}
private static class Student {
String name;
String nationality;
String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", nationality='" + nationality + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
}
First of all, it would be better if you put your while loop inside the try block because you don't want to get there if the file hasn't been found.
Second, you don't need to create a new instance of Scanner just to read every line. You can simply read your file word by word:
while (sc2.hasNext())
readword.add(sc2.next());
To group the students according to their nationality, you can do something like that:
String nationality = [UserInput] ;
List<String> group = new ArrayList<>();
for (int i = 0; i < readword.size(); i++)
if (readword.get(i + 1).equals(nationality)
group.add(readword.get(i));

Person tester application with inheritance and abstract classes

I apologize in advance if there is more posts about this, I have looked through the postings that appeared relevant but could not find a solution. I working on a project called a Person Tester in which;
the user is prompted to chose between creating a customer (c) or an employee (e).
next, the user is prompted to enter first, last name, e-mail adress and either customer number (if customer is selected), or social security number (if employee is selected).
once the correct data has been gathered, the information is suposed to be printed to the console in this format:
name: first last
email: jondoe#fakemail.com
social security number: XXXXXXXXXXX (if employee)
customer number: XXXXXX (if customer)
this program deals with inheritance and an abstract person class which is extended by an employee class and a customer class. another stipulation states that the person class should contain an abstract method named getDisplayText that returns a string.
this is where my problem lies, this is my first time working with abstract classes.
MY QUESTION is why cant I simply print the toString method in my perosn class to display all the user data that was entered which brings me to my next issue, the program needs to have an additional component which is (and I quote from my assignment) : To print the data for an object to the console, this application should use a static method named print that accepts a Person object.
im not sure how to implement this since it was never discussed in class. I have tried to simply code the following : System.out.print(aPerson.toString) but all i get is blank value of Name: and Social Security number: . Im going nuts i have been working on this for several hours and re-read the relevant text at least 4 times. this is my last resort. please guide me in the right direction i dont mind working long hours to do this right.
I have written the majority of the application and am now just stuck on how to print the data to the console. any and all suggestions are appreciated, this is my code:
public class CH08PR82App {
public static void main(String[] args) {
System.out.print("Welcome to the Person Tester Application");
System.out.println();
Scanner sc = new Scanner(System.in);
Person aPerson;
aPerson = new Person();
if (aPerson != null) {
System.out.println(aPerson.toString());
}
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
//prompt user to enter customer or employee
System.out.print("Create customer or employee (c/e): ");
String userType = sc.nextLine();
if (userType.equalsIgnoreCase("c")) {
String firstName = Validator.getStringInput(sc, "Enter first name: ");
String lastName = Validator.getStringInput(sc, "Enter last name: ");
String email = Validator.getStringInput(sc, "Enter email address: ");
String custNumber = Validator.getStringInput(sc, "Customer number: ");
//System.out.println(custNumber);
} else if (userType.equalsIgnoreCase("e")) {
String firstName = Validator.getStringInput(sc, "Enter first name: ");
String lastName = Validator.getStringInput(sc, "Enter last name: ");
String email = Validator.getStringInput(sc, "Enter email address: ");
int empSoc = Validator.getInt(sc, "Social security number: ");
}
choice = Validator.getStringContinue(sc, "Continue? (y/n): ");
}
}
}
abstract class Person {
private String firstName;
private String lastName;
private String eMail;
public Person() {
firstName = "";
lastName = "";
eMail = "";
}
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 geteMail() {
return eMail;
}
public void seteMail(String eMail) {
this.eMail = eMail;
}
#Override
public String toString() {
return "Name: " + this.firstName + this.lastName + "\n" + "E-mail: "
+ this.eMail;
}
abstract String getDisplayText();
}
abstract class Customer extends Person {
private String customerNumber;
public Customer() {
super.toString();
customerNumber = "";
}
public void setcustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;
}
public String getcustomerNumber() {
return customerNumber;
}
#Override
public String toString() {
return super.toString() + "Social Security number: " + customerNumber
+ "\n";
}
}
abstract class Employee extends Person {
private String socNumber;
public Employee() {
super.toString();
socNumber = "";
}
public void setsocNumber(String socNumber) {
this.socNumber = socNumber;
}
public String getsocNumber() {
return socNumber;
}
#Override
public String toString() {
return super.toString() + "Social Security number: " + socNumber
+ "\n";
}
}
class Validator {
public static String getStringContinue(Scanner sc, String prompt) {
boolean isValid = false;
String s = "";
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNext("y")) {
s = sc.nextLine(); // read entire line
isValid = true;
} else if (sc.hasNext("n")) {
s = sc.nextLine();
isValid = true;
} else {
s = sc.nextLine();
isValid = false;
System.out.println("Error! Invalid string value. Try again.");
}
}
return s;
}
public static String getStringInput(Scanner sc, String prompt) {
boolean isValid = false;
String s = "";
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNext()) {
s = sc.nextLine(); // read entire line
isValid = true;
} else {
System.out.println("Error! Invalid string value. Try again.");
}
}
return s;
}
public static int getInt(Scanner sc, String prompt) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNextInt()) {
i = sc.nextInt();
isValid = true;
} else {
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public static int getInt(Scanner sc, String prompt, int min, int max) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
i = getInt(sc, prompt);
if (i <= min) {
System.out.println("Error! Number must be greater than " + min
+ ".");
} else if (i >= max) {
System.out.println("Error! Number must be less than " + max
+ ".");
} else {
isValid = true;
}
}
return i;
}
public static double getDouble(Scanner sc, String prompt) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNextDouble()) {
d = sc.nextDouble();
isValid = true;
} else {
System.out.println("Error! Invalid decimal value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}
public static double getDouble(Scanner sc, String prompt, double min,
double max) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
d = getDouble(sc, prompt);
if (d <= min) {
System.out.println("Error! Number must be greater than " + min
+ ".");
} else if (d >= max) {
System.out.println("Error! Number must be less than " + max
+ ".");
} else {
isValid = true;
}
}
return d;
}
}
Let's take a look at the print method first:
public static void print(Person person) {
System.out.println(person.toString());
}
Now you need an abstract method in your Person class:
public abstract String getDisplayText(Person person);
Which you will override in your Employee and Customer classes:
// Employee
#Override
public String getDisplayText(Person person) {
return ((Employee)person).toString();
}
and:
// Customer
#Override
public String getDisplayText(Person person) {
return ((Customer)person).toString();
}
They wanted you to make the method abstract because each implementation is different - Customer has a customer ID, Employee has a Soc Number.
Now lets explain static and abstract methods: The difference between a static and abstract method is that an abstract method is just a header - implementation lies on children classes. Whereas a static method means that you can call it without creating an object in the first place.
Usage of this specific static method is very simple. Lets say you have:
Person john = new Customer();
... // Fill john with data
Person.print(john);
It also looks to me like you are a bit confused about all this abstract and static stuff. An abstract class is a class which can't create objects. In your example, you have an abstract class Person. The class is abstract because you either need a customer or an employee (both of which are people, hence the inheritance from Person class), but you don't want to store info about a person who is none of these. And that is also the reason why you can't do:
Person john = new Person(); // Build error
but you can (and should) do:
Person john = new Employee(); // Will compile and run

(non-static method Change(String,String,String) cannot be referenced from a static context

I've searched, but didn't understand how to incorporate previous answers with my own code. I have an assigment to create a draft of a program for the schools "bank/scholarship"-system. Here we need to create a lot of different methods, that should be called instead of just doing the change directly.
The thing is, I keep getting the error-message in the topic along with a few others, and I don't know how to fix it. I would really appreciate if someone could explain for me how and why to change one of my methods, then I assume I will be able to rewrite all the others myself. Here is my code so far:
class Address
public class Address {
public String street, zip, post;
public Address (String street, String zip, String post) {
this.street = street;
this.zip = zip;
this.post = post;
}
// these are setters (mutators)
public void setStreet (String street) {
this.street = street; }
public void setZip (String zip) {
this.zip = zip; }
public void setPost (String post) {
this.post = post; }
// these are getters
public String getStreet () {
return this.street; }
public String getZip () {
return zip; }
public String getPost () {
return post; }
// methods
//public Address Change(Address newAddress) {
//return newAddress;
//}
// output
public String toString() {
return (street + ", " + zip + ", "+ post); }
}
class Customer
import java.text.DecimalFormat;
public class Customer {
DecimalFormat twoD = new DecimalFormat("0.00");
Address address = new Address("Vik ", "6393 ", "Tomrefjord");
public String name, campus, newCampus, newAddress;
public double loan, increase,decrease,regMaster;
public boolean finished;
public Customer (String name,Address address, String campus, double loan, boolean finished) {
this.name = name;
this.campus = campus;
this.loan = loan;
this.address = address;
this.finished = finished;
}
// these are setters
public void setName (String name) {
this.name = name; }
public void setCampus (String campus) {
this.campus = campus; }
public void setLoan (double loan) {
this.loan = loan; }
public void setFinished (boolean finished) {
this.finished = finished; }
// these are getters
public String getName () {
return name; }
public String getCampus () {
return campus; }
public double getLoan () {
return loan; }
// methods
public void RegMaster () {
this.loan = loan * 0.90;}
//public void changeAddress (Address newAddress) {
//Address.Change(newAddress); }
public double decreaseLoan (double currentBalance, double decrease) {
currentBalance = currentBalance - decrease;
return currentBalance; }
public double getNewLoan (double currentBalance, double newLoan) {
newLoan = currentBalance + newLoan;
return newLoan; }
public String getNewCampus (String newCampus) {
campus = newCampus;
return campus; }
public static boolean Ended () {
return true; }
// output
public String toString() {
return (name + "\t\n" + address + "\t\n" + campus + "\t\n" + twoD.format(loan) + "\t\n" + finished); }
}
class TestCustomer
import java.util.Scanner;
public class TestCustomer {
public static void main (String[] args) {
String student, school, answer, street, zip, post;
double balance, master;
boolean finished = false;
double done = 0; //this is for the loop
Scanner scan = new Scanner(System.in);
// a new student receives a loan
System.out.println("Write your name");
student = scan.nextLine();
System.out.println("Enter your street name and number");
street = scan.nextLine();
System.out.println("What is your zip code?");
zip = scan.nextLine();
System.out.println("What is your post area?");
post = scan.nextLine();
System.out.println("Where do you study?");
school = scan.nextLine();
System.out.println("Input your current loan");
balance = scan.nextDouble();
Address residence = new Address(street, zip, post);
Customer customer = new Customer(student, residence, school, balance, finished);
while(done < 1) { //the variable done will have the value 0 until you are finished.
// change address
System.out.println("Do you wish to change your address? (yes/no)");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) { //this made it case-insensitive, and now it is not skipping anymore...
System.out.println("Write your street name and house number");
street = scan.nextLine();
System.out.println("Write your zip code");
zip = scan.nextLine();
System.out.println("Write your post area");
post = scan.nextLine();
//Address newAddress = new Address(street, zip, post);
//residence = Customer.changeAddress(newAddress);
}
// increase the loan
System.out.println("Do you want to increase your loan? (yes/no)");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) {
System.out.println("How much do you need?");
double increaseLoan = scan.nextDouble();
//customer.balance = getNewLoan(customer.balance, moreLoan);
}
// decrease the loan
System.out.println("Do you want to make a downpayment on your loan?");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) {
System.out.println("How much do you intend to pay?");
double downpayment = scan.nextDouble();
//customer.balance = decreaseLoan(customer.balance, downpayment);
}
// change school
System.out.println("Do you study at the same school? (yes/no");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("no")) {
System.out.println("Write the name of the new school");
school = scan.nextLine(); }
//school.getNewCampus(customer.campus);
// master check
System.out.println("Have you finished your master? (yes/no)");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) {
customer.finished = Customer.Ended() ; //this will set finished to true, using the method like intended
//customer.balance = Customer.RegMaster(); // dont know how to invoke it... me neither -_-
}
System.out.println("Are you done? yes/no");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) {
done = 1; } // this adds 1 to the variable done, thus ending the loop.
}
// output
System.out.println("");
System.out.println("The data we have so far is:");
System.out.println(customer);
}}
Here are all three of my classes. Some of the functions are commented away, others are just not working properly (the code is also a little extra messy, I was changing back and forth to try to get it working yesterday). Any help will be appreciated! :)
Okay, from you comment then your problem comes from the (helpfully) commented out lines
//public void changeAddress (Address newAddress) {
//Address.Change(newAddress); }
This is because your Customer done not "have an" Address, you need an address instance and not a String:
private Address address;
public Customer (final Address address) {
this.address = address;
}
I have redacted other variables for clarity. Incidentally I would use a builder pattern rathen than one enormous constructor.
Now that you have an Address in your Customer:
public void changeAddress (Some parameters to change) {
address.setStuff();
}
I would recommend that you read this link about the difference between static and instance variables.

Need help deleting from Arraylist with remove

Ok, this is homework. I have an arraylist assignment to add, display, search and remove contacts. My code compiles and I have all of the correct methods that function properly EXCEPT for the deleteMatch() method. It compiles and runs, but does not actually remove anything from my arrayList. I also need to go back once done and validate input and check for nulls I know, but I can do that easliy, I'm just trying to get the basics in first. Any help with this method would be greatly appreciated.
import java.util.ArrayList;
import java.util.Scanner;
public class ContactDatabase
{
private ArrayList<Contact> contacts; // ArrayList of contact
private static final int QUIT = 0; // Menu choices
private static final int ADD = 1;
private static final int LISTALL = 2;
private static final int SEARCH = 3;
private static final int DELETE = 4;
/**
* Default constructor - make a new ArrayList object with parameter type Contact,,
*/
ContactDatabase()
{ // Initialize the categories.// instantiate your ArrayList here
contacts = new ArrayList<Contact>();
}
/**
* inputContact inputs contact information from the keyboard.
* It then stores this new contact in the contacts ArrayList.
*/
public void inputContact()
{
Contact myContact;
Scanner input = new Scanner(System.in);
System.out.println("Please enter first name of new person");
String first = input.nextLine();
System.out.println("Please enter last name of new person");
String last = input.nextLine();
System.out.println("Please enter phone number xxxxxxxxxx");
String phone = input.nextLine();
System.out.println("Please enter e-mail");
String email = input.nextLine();
myContact = new Contact(first, last, phone, email);
contacts.add(myContact);
System.out.println("Details recorded:");
System.out.println(contacts);
}
/**
* displayAll iterates through the ArrayList of contacts and outputs each one
* to the screen.
*/
public void displayAll()
{
for (Contact entry : contacts)
System.out.println (entry);
}
/**
* displayMatch inputs a keyword from the user.
* It then iterates through the ArrayList of contacts and outputs each one
* to the screen if the contact information contains the keyword.
*/
public void displayMatch()
{
if(contacts.isEmpty())
{
System.out.println("Sorry, there is no contact information to search.");
}
else
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter the search keyword for or 0 to quit: ");
String search = input.next().trim().toUpperCase();
if (search.equals("0") == false)
{
boolean found = false;
for(Contact a: contacts)
{
if((a.getFirst().toUpperCase().equals(search))||(a.getLast().toUpperCase().equals(search))||(a.getPhone().toUpperCase().equals(search))||(a.getEmail().toUpperCase().equals(search)))
{
System.out.println("that contact info is: ");
System.out.println("name: " + a.getFirst());
System.out.println("name: " + a.getLast());
System.out.println("phone number: " + a.getPhone());
System.out.println("email: " + a.getEmail());
found = true;
}
else
{
found = false;
System.out.println("Sorry, that contact can not be found!");
}
}
}
}
}
/**
* deleteMatch inputs a keyword from the user.
* It then iterates through the ArrayList of contacts and asks the user
* if the contact should be deleted, if the contact information contains the keyword.
*/
public void deleteMatch()
{
if(contacts.isEmpty())
{
System.out.println("Sorry, there is no contact information to search.");
}
else
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter the search keyword for or 0 to quit: ");
String search = input.next().trim().toUpperCase();
if (search.equals("0") == false)
{
boolean found = false;
for(Contact a: contacts)
{
if((a.getFirst().toUpperCase().equals(search))||(a.getLast().toUpperCase().equals(search))||(a.getPhone().toUpperCase().equals(search))||(a.getEmail().toUpperCase().equals(search)))
{
System.out.println("that contact info is: ");
System.out.println("name: " + a.getFirst());
System.out.println("name: " + a.getLast());
System.out.println("phone number: " + a.getPhone());
System.out.println("email: " + a.getEmail());
found = true;
Scanner inp = new Scanner(System.in);
System.out.println("Are you sure you would like to remove this contact?");
String sure = inp.next().toUpperCase();
if (sure.equals("YES"))
{
contacts.remove(a);
System.out.println("Contact removed... ");
displayAll();
}
}
else
{
found = false;
System.out.println("Sorry, that contact can not be found!");
}
}
}
}
}
// run through the array and look for an item that matches e
// get keyword input from user to be used in search
// run through list and look for any Contact that has
// the keyword
// prompt user to make sure they want to delete the
// (next/current) Contact you found
// if yes, delete the Contact
// Main class
public static void main(String[] args)
{
ContactDatabase cdb = new ContactDatabase();
Scanner scan = new Scanner(System.in);
int choice = ADD;
// Main menu
while (choice != QUIT)
{
System.out.println();
System.out.println("Choose from the following:");
System.out.println("0) Quit");
System.out.println("1) Add new contact");
System.out.println("2) List all contacts");
System.out.println("3) Search contacts by keyword and display");
System.out.println("4) Search contacts by keyword and remove");
choice = scan.nextInt();
switch (choice)
{
case ADD: cdb.inputContact();
break;
case LISTALL: cdb.displayAll();
break;
case SEARCH: cdb.displayMatch();
break;
case DELETE: cdb.deleteMatch();
break;
}
}
}
class Contact
{
private String first, last, phone, email;
/**
* Constructors.
*/
public Contact()
{
}
public Contact(String first, String last, String phone, String email)
{
this.first = first;
this.last = last;
this.phone = phone;
this.email = email;
}
/*
* Accessor Methods
*/
public String getFirst()
{
return first;
}
public String getLast()
{
return last;
}
public String getPhone()
{
return phone;
}
public String getEmail()
{
return email;
}
/*
* Mutator Methods
*/
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 void setEmail(String em)
{
this.email = em;
}
/*
* Return all fields concatenated into a string
*/
public String toString()
{
return last + ", " + first + ". " + phone + ", " + email;
}
public boolean equals(Object otherObject)
{
if (otherObject ==null)
{
return false;
}
else if (getClass() != otherObject.getClass())
{
return false;
}
else
{
Contact otherContact = (Contact)otherObject;
return (first.equals(otherContact.first) &&
last.equals(otherContact.last)&&
phone.equals(otherContact.phone)&&
email.equals(otherContact.email));
}
}
} // end inner class, Contact
} // end class, ContactDatabase
Thank you to everyone for your help. I finally got it to work!!! Here is the final code:
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The ContactDatabase class stores each contact in an arraylist.
* Methods exist to add new contacts, search contacts, delete, and print contacts
* to the console.
*/
public class ContactDatabase
{
private ArrayList<Contact> contacts; // ArrayList of contact
private static final int QUIT = 0; // Menu choices
private static final int ADD = 1;
private static final int LISTALL = 2;
private static final int SEARCH = 3;
private static final int DELETE = 4;
/**
* Default constructor - make a new ArrayList object with parameter type Contact,,
*/
ContactDatabase()
{
contacts = new ArrayList<Contact>();
}
/**
* inputContact inputs contact information from the keyboard.
* It then stores this new contact in the contacts ArrayList.
*/
public void inputContact()
{
Contact myContact;
String first = "null";
String last = "null";
String phone = "000-0000000";
String email = "xxx#example.com";
Scanner input = new Scanner(System.in);
while (true)
{
System.out.println("Please enter first name of new person");
first = input.nextLine();
if (first == null)
{
System.out.println("Sorry, first name cannot be null!");
}
else
{
break;
}
}
while (true)
{
System.out.println("Please enter last name of new person");
last = input.nextLine();
if (first == null)
{
System.out.println("Sorry, last name cannot be null!");
}
else
{
break;
}
}
while (true)
{
System.out.println("Please enter phone number 540-555-1212");
String vphone = input.nextLine();
Pattern pattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");
Matcher matcher = pattern.matcher(vphone);
if ((matcher.matches())|| vphone != null)
{
System.out.println("Thank you.");
phone = vphone;
break;
}
else
{
System.out.println("Sorry, that entry is incorrect or null");
}
}
while (true)
{
System.out.println("Please enter e-mail xyz#xyz.com");
String vemail = input.nextLine();
Pattern pattern = Pattern.compile(".+#.+\\.[a-z]+");
Matcher matcher = pattern.matcher(vemail);
if ((matcher.matches())||(vemail != null))
{
System.out.println("Thank you.");
email = vemail;
break;
}
else
{
System.out.println("Sorry, that entry is incorrect");
}
}
myContact = new Contact(first, last, phone, email);
contacts.add(myContact);
System.out.println("Details recorded:");
System.out.println(contacts);
}
/**
* displayAll iterates through the ArrayList of contacts and outputs each one
* to the screen.
*/
public void displayAll()
{
System.out.println("Current contact list entries:");
for (Contact entry : contacts)
System.out.println (entry);
}
/**
* displayMatch inputs a keyword from the user.
* It then iterates through the ArrayList of contacts and outputs each one
* to the screen if the contact information contains the keyword.
*/
public void displayMatch()
{
boolean found = false;
Scanner input = new Scanner(System.in);
System.out.print("Please enter the search keyword for or 0 to quit: ");
String search = input.next().trim().toUpperCase();
if (search.equals("0") == false)
{
for(Contact a: contacts)
{
if((a.getFirst().toUpperCase().equals(search))||(a.getLast().toUpperCase().equals(search))||(a.getPhone().toUpperCase().equals(search))||(a.getEmail().toUpperCase().equals(search)))
{
System.out.println("that contact info is: ");
System.out.print("name: " + a.getFirst());
System.out.println(" " + a.getLast());
System.out.println("phone number: " + a.getPhone());
System.out.println("email: " + a.getEmail());
found = true;
}
if(contacts.isEmpty())
{
System.out.println("Sorry, there is no contact information to search.");
}
}
}
if (found == false)
{
System.out.println("Sorry, no such contact");
}
}
/**
* deleteMatch inputs a keyword from the user.
* It then iterates through the ArrayList of contacts and asks the user
* if the contact should be deleted, if the contact information contains the keyword.
*/
public void deleteMatch()
{
for (int i=0; i< contacts.size(); i++)
{
displayMatch();
Scanner inp = new Scanner(System.in);
System.out.println("Are you sure you would like to remove this contact?");
String sure = inp.next().toUpperCase();
if (sure.equals("YES"))
{
contacts.remove(i);
System.out.println("Thank you. Contact removed.");
displayAll();
}
}
}
// Main class
public static void main(String[] args)
{
ContactDatabase cdb = new ContactDatabase();
Scanner scan = new Scanner(System.in);
int choice = ADD;
// Main menu
while (choice != QUIT)
{
System.out.println();
System.out.println("Choose from the following:");
System.out.println("0) Quit");
System.out.println("1) Add new contact");
System.out.println("2) List all contacts");
System.out.println("3) Search contacts by keyword and display");
System.out.println("4) Search contacts by keyword and remove");
choice = scan.nextInt();
switch (choice)
{
case ADD: cdb.inputContact();
break;
case LISTALL: cdb.displayAll();
break;
case SEARCH: cdb.displayMatch();
break;
case DELETE: cdb.deleteMatch();
break;
}
}
}
/**
* The inner class, Contact, stores the details for a single contact.
* There is no error checking on any of the input. Whatever string is
* passed in for a given attribute is accepted.
*/
class Contact
{
private String first, last, phone, email;
/**
* Constructors.
*/
public Contact()
{
}
public Contact(String first, String last, String phone, String email)
{
this.first = first;
this.last = last;
this.phone = phone;
this.email = email;
}
/*
* Accessor Methods
*/
public String getFirst()
{
return first;
}
public String getLast()
{
return last;
}
public String getPhone()
{
return phone;
}
public String getEmail()
{
return email;
}
/*
* Mutator Methods
*/
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 void setEmail(String em)
{
this.email = em;
}
/*
* Return all fields concatenated into a string
*/
public String toString()
{
return last + ", " + first + ". " + phone + ", " + email;
}
public boolean equals(Object otherObject)
{
if (otherObject ==null)
{
return false;
}
else if (getClass() != otherObject.getClass())
{
return false;
}
else
{
Contact otherContact = (Contact)otherObject;
return (first.equals(otherContact.first) &&
last.equals(otherContact.last)&&
phone.equals(otherContact.phone)&&
email.equals(otherContact.email));
}
}
} // end inner class, Contact
} // end class, ContactDatabase
If you have overridden the equals method you dont need to check for individual fields , yoy can simply create a new contact with new information and then just call arrayList.remove(contact_ob); it will remove if it exists,
also for comparing string you are using string.toUpper().equals(other_str); instead you can use string.equalsIgnoreCase(otherString) , will compare irrespective of the case
you are trying to remove(object) which is not correct.
Remove the object based on the index or counter... Tis will surely solve your problem.
And between when u try to remove the objct based on the object
This will solve your problem for now,, but think about overriding the equals method and remove the object
There are few things that you need to change in this code.
1] Match with equalsIgnoreCase. Never convert a value to upper or lower case and then match it. It constraints the user to enter a specific case.
2] While entering you need to check for duplicate values which have already been entered.
3] You need to break once you have searched for a particular contact and removed it.
4] Always make a Contact object and then use it for match.

Categories

Resources