Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Scanner;
- public class ArrayListTest {
- /*
- This code not working as it should. Problem is: arraylist is of type Person (a class).
- The contains() method is not recognising elements (works with type String, but not Person.)
- See comments in first two methods.
- */
- public static ArrayList<Person> friendList = new ArrayList<Person>();
- public void addFriend(Person p) {
- /* Do not add duplicates
- if p==this, do nothing
- */
- if (!(friendList.contains (p))) { /// contains not working - says doesn't contain
- friendList.add (p);
- } else {
- System.out.println("Not added!"); // for test purposes
- }
- }
- public boolean deleteFriend(Person p) {
- /* Return true if and only if p was found;
- otherwise should do nothing and return false
- */
- if (friendList.contains (p)) { /// contains not working - says doesn't contain
- friendList.remove (p);
- System.out.println ("Removed: "+p.toString()); // for test purposes
- return true;
- }
- return false;
- }
- public Person getPerson(Scanner scan) {
- System.out.print("Enter name: ");
- String name = scan.nextLine();
- Person p = new Person();
- p.setName(name);
- return p;
- }
- public static void main(String[] args) {
- ArrayListTest test = new ArrayListTest();
- Scanner scan = new Scanner(System.in);
- String choice="";
- String again="";
- do {
- do {
- System.out.print("Add or remove person (a/r)(x=exit)? ");
- choice = scan.nextLine().toLowerCase();
- } while (!(choice.equals("a") || choice.equals("r") || choice.equals("x")));
- Person p = test.getPerson(scan);
- if (choice.equals("a")) {
- test.addFriend(p);
- } else if (choice.equals("r")) {
- if (test.deleteFriend (p)) {
- System.out.println("Deleted.");
- } else {
- System.out.println("Not found!");
- } // if
- } else if (choice.equals("x")) {
- break;
- } // if
- for (Person friend: friendList) {
- System.out.println (friend.toString());
- } // for
- System.out.print("Again (y/n)? ");
- again = scan.nextLine().toLowerCase();
- } while (!again.startsWith("n"));
- } // main()
- } // class ArrayListTest
- class Person {
- private String name;
- public Person() {
- name = "";
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getName() {
- return this.name;
- }
- public String toString() {
- return this.name;
- }
- } // class Person
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement