【问题标题】:Arraylist methods doesn't workArraylist 方法不起作用
【发布时间】:2016-05-01 23:09:48
【问题描述】:

一切都很好,除了 displayMatch() 和 deleteMatch() 结果显示为“无匹配”,而我输入的输入有一些匹配

这部分问题可能会有所帮助

enter image description here

import java.util.ArrayList;
import java.util.Scanner;
import java.lang.*;


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()
{
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter first and last names: ");
    String firstName = input.next();
    String lastName = input.nextLine();
    /*  while (input != null || input != " ") {
            //firstLast = input.nextLine();
        }
    contacts.add(firstName);
    contacts.add(lastName);
    */
    System.out.println("Now enter " + firstName + " " + lastName + "\'s email address: ");
    String emailAddress = input.nextLine();

        if (emailAddress.indexOf('@') < 0) {
            System.out.println("No '@' in email address\n Please enter a correct email address: ");
        }

        if (emailAddress.indexOf('.') < 0) {
            System.out.println("No '.' in email address!");
        } else {
            //emailAddress = input.nextLine();
            System.out.println("Email address accepted!");
        }

    System.out.println("Please enter " + firstName + " " + lastName + "\'s phone number: ");
    String phoneNumber = input.nextLine();

        boolean number = false;
        int n = 0;
        while (n < phoneNumber.length()) {
            char c = phoneNumber.charAt(n);

            if (!(c >= '0' && c <= '9'))
                number = false;
                n++;
        }
        number = true;

        phoneNumber = phoneNumber.replaceAll("\\-","");
        phoneNumber = phoneNumber.replaceAll("\\(","");
        phoneNumber = phoneNumber.replaceAll("\\)","");
    System.out.println("Phone number accepted.");

    Contact newContact = new Contact(firstName, lastName, phoneNumber, emailAddress);
    contacts.add(newContact);
    System.out.println(firstName + "" + lastName + " has been added as a contact.");
}

/**
* displayAll iterates through the ArrayList of contacts and outputs each one
* to the screen.
*/
public void displayAll()
{   

    System.out.println("Your contacts are: ");
    for (Contact c : contacts)
    {   
        if (contacts.isEmpty()) {
            System.out.println("No contacts.");
        } else {
            System.out.println(c);
        }
    }   
}

/**
* 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()
{

    System.out.println("Enter keyword: ");
    Scanner input = new Scanner(System.in);
    String in = input.next();

        for (Contact c : contacts)
        {
            if (in.equals(c)) {
                System.out.println(c);
            } else {
                System.out.println("No matches.");
            }
        }   
}

/**
* 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()
{

    System.out.println("Enter keyword: ");
    Scanner input = new Scanner(System.in);
    String in = input.next();

    for (Contact c : contacts) 
    {
        if (in.equals(c)) {
            System.out.println("Should " + c + " be deleted? (type 'YES' or 'Y')");
            //in = input.nextLine();

            boolean done = false;
            while (! done)
            {   
                if (in.equalsIgnoreCase("yes") || in.equalsIgnoreCase("y")) {
                    contacts.remove(c);
                } else {
                    done = true;
                }
            }   

        } else {
            System.out.println("No matches!");
        }
    }
}

// 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

【问题讨论】:

标签: java arraylist methods


【解决方案1】:

嗯,您正在将您在 displayMatch() 方法中读取的字符串与您的联系人列表中的元素进行比较:

in.equals(c)

由于字符串不能等于联系人,因此您的列表将保持为空。

您可以更改 Contact 类中的 equals() 方法,以将其内容与给定的字符串进行比较(最后一个成员的示例:)

public boolean equals(Object otherObject)
   {
      if (otherObject == null)
      {
         return false;
      }
      else if (otherObject instanceof String) {
         String otherString = (String) otherObject;
         String lowerCaseString = otherString.toLowerCase();
         return this.last != null && this.last.toLowerCase().contains(lowerCaseString);
      }
      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));
      }
   }

然后使用

c.equals(in);

改为。

【讨论】:

  • 我不明白这部分 return this.last != null && this.last.toLowerCase().contains(((String)otherObject.toLowerCase())); toLowerCase() 和 (String) 是什么意思
  • 我已将该行分解为单个语句。 toLowerCase() 只是一种使 String 的所有字符变小的方法(TeXt -> text) 由于 equals 方法接受一个对象作为输入参数,因此我们必须检查具体类型。如果它是一个字符串,我们希望像处理它一样处理它。这就是铸造操作员正在做的事情。
猜你喜欢
  • 2016-08-30
  • 1970-01-01
  • 2017-07-31
  • 2016-02-02
  • 1970-01-01
  • 2013-10-31
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多