我需要我的程序检测其联系人列表中的先前条目,并禁止用户输入两个相同的条目。我一直在尝试,但是我要么允许所有条目,要么无效的条目仍保存到我的列表中。

我想要做的是使它的程序成为电话簿,并且现实生活中没有两个人应该有相同的电话号码。这就是为什么我希望只有给定号码的一个联系人。

这是我检查条目的代码:

System.out.print("Enter Number: ");
    number = stdin.nextLine(); // read the number

    while(!number.matches(pattern)) { // as long as user doesnt enters correct format, loop
        System.out.println("Error!");
        System.out.println("Not proper digit format! Use \"012-3456\", \"(012)345-6789\"" +
                ", or \"012-345-6789\" format.");
        System.out.print("Enter number: ");
        number = stdin.nextLine();
    }
    for (Entry e : contactList) {
        if (e.number.equals(number)) {
            System.out.println("This phone number already exist. Please check contacts.");
            System.out.println("");
            return;
        }else{
            break;
        }
    }
    contactList[num_entries].number = number;


这是我的完整代码供参考:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;

class Entry {
public String fname, lname, number, note;
}
class PBN {
public static Entry[] contactList;
public static int num_entries;
public static Scanner stdin = new Scanner(System.in);
public static void main(String args[]) throws Exception{

    Scanner s = new Scanner(System.in);
    int i;
    char C;
    String code, Command;
    contactList = new Entry[999];
    num_entries = 0;
    try {
        readPhoneBook("PhoneBook.txt");
    } catch (FileNotFoundException e) {}
    System.out.println("Codes are entered as 1 to 8 characters.\n" +
            "Use Commands:\n" +
            " \"e\" for enter a new contact,\n" +
            " \"f\" for find contact by fist name,\n" +
            " \"r\" for find contact by last name,\n" +
            " \"y\" for find contact by phone number,\n" +
            " \"l\" for listing all the existing contacts,\n" +
            " \"d\" for removing contacts by phone number,\n" +
            " \"a\" for sort alphabetically by first name,\n" +
            " \"n\" for sort alphabetically by last name,\n" +
            " \"p\" for sort by number,\n" +
            " \"q\" to quit.");
    Command = null;
    C = ' ';
    while(true) { // loop infinitely

        System.out.print("Command: ");
        Command = stdin.nextLine();
        C = Command.charAt(0);
        switch (C) {
            case 'e': addContact(); break;
            case 'f':
                System.out.print("Search for contact by first name: ");
                code = stdin.next();
                stdin.nextLine();
                index(code); break;
            case 'r':
                System.out.print("Search for contact by last name: ");
                code = stdin.next();
                stdin.nextLine();
                index1(code); break;
            case 'y':
                System.out.print("Search for contact by phone number: ");
                code = stdin.next();
                stdin.nextLine();
                index2(code); break;
            case 'l':
                listAllContacts(); break;
            case 'q': // when user wants to quit
                CopyPhoneBookToFile("PhoneBook.txt");
                System.out.println("Quitting the application. All the entries are "
                        + "stored in the file PhoneBook1.txt");
                System.exit(0); // simply terminate the execution
            case 'a':
                sortList1();
                break;
            case 'n':
                sortList2();
                break;
            case 'p':
                sortListByPhoneNumber();
                break;
            case 'd': // m for deleting a contact; delete by phone number
                System.out.print("Enter the phone number of a contact you wish to delete : ");
                String number = stdin.nextLine();// read the contact number
                removeEntry1(number); // remove the number from the entries
                break;
            default:
                System.out.println("Invalid command Please enter the command again!!!");
        }
    }
}
public static void readPhoneBook(String FileName) throws Exception {
    File F;
    F = new File(FileName);
    Scanner S = new Scanner(F);
    while (S.hasNextLine()) {
        contactList[num_entries]= new Entry();
        contactList[num_entries].fname = S.next();
        contactList[num_entries].lname = S.next();
        contactList[num_entries].number = S.next();
        contactList[num_entries].note = S.nextLine();
        num_entries++;
    }
    S.close();
}
public static void addContact() {
    System.out.print("Enter first name: ");
    String fname = stdin.nextLine();
    String lname;
    String number;
    String pattern = "^\\(?(\\d{3})?\\)?[- ]?(\\d{3})[- ](\\d{4})$";
    while (fname.length() > 8 || fname.length() < 1) {
        System.out.println("First name must be between 1 to 8 characters.");
        System.out.print("Enter first name: ");
        fname = stdin.nextLine();
    }
    contactList[num_entries] = new Entry();
    contactList[num_entries].fname = fname;
    System.out.print("Enter last name: ");
    lname = stdin.nextLine();
    while (lname.length() > 8 || lname.length() < 1) {
        System.out.println("First name must be between 1 to 8 characters.");
        System.out.print("Enter first name: ");
        lname = stdin.nextLine();
    }
    contactList[num_entries].lname = lname;
    System.out.print("Enter Number: ");
    number = stdin.nextLine(); // read the number

    while(!number.matches(pattern)) { // as long as user doesnt enters correct format, loop
        System.out.println("Error!");
        System.out.println("Not proper digit format! Use \"012-3456\", \"(012)345-6789\"" +
                ", or \"012-345-6789\" format.");
        System.out.print("Enter number: ");
        number = stdin.nextLine();


        for (Entry e : contactList) {
            if (e.number.equals(number)) {
                System.out.println("This phone number already exist. Please check contacts.");
                System.out.println("");
                break;
            } else {
                return;
            }
        }
    }
    contactList[num_entries].number = number;

    System.out.print("Enter Notes: ");
    contactList[num_entries].note = stdin.nextLine();

    num_entries++;
    System.out.println();
}
public static void listAllContacts() {
    for(Entry e : contactList) {
        if(e != null)
            displayContact(e);
        else
            break;
    }
}
public static int index(String Key) {
    // Function to get the index of a key from an array
    // if not found, returns -1
    for (int i=0; i < num_entries; i++) {
        if (contactList[i].fname.equalsIgnoreCase(Key)) {
            if (i >= 0) displayContact(contactList[i]);
            //return i;
        }    // Found the Key, return index.
    }
    return -1;
}
public static int index1(String Key) {
    // Function to get the index of a key from an array
    // if not found, returns -1
    for (int i=0; i < num_entries; i++) {
        if (contactList[i].lname.equalsIgnoreCase(Key)) {
            if (i >= 0) displayContact(contactList[i]);
            //return i;
        }    // Found the Key, return index.
    }
    return -1;
}
public static int index2(String Key) {
    // Function to get the index of a key from an array
    // if not found, returns -1
    for (int i=0; i < num_entries; i++) {
        if (contactList[i].number.equalsIgnoreCase(Key)) {
            if (i >= 0) displayContact(contactList[i]);
            //return i;
        }    // Found the Key, return index.
    }
    return -1;
}
public static void displayContact(Entry contact) {
    System.out.println("--"+ contact.fname+"\t");
    System.out.println("--"+ contact.lname+"\t");
    System.out.println("--"+ contact.number+"\t");
    System.out.println("--"+ contact.note);
    System.out.println("");
}

public static void sortList1() {
    int i;
    Entry temp;
    temp = new Entry();
    for (int j = 0; j< num_entries; j++) {
        for (i = j + 1; i < num_entries; i++) {
            if (contactList[j].fname.compareToIgnoreCase(contactList[i].fname)> 0) {
                temp = contactList[j];
                contactList[j] = contactList[i];
                contactList[i] = temp;
            }
        }
    }listAllContacts();
}
public static void sortList2() {
    int i;
    Entry temp;
    temp = new Entry();
    for (int j = 0; j< num_entries; j++) {
        for (i = j + 1; i < num_entries; i++) {
            if (contactList[j].lname.compareToIgnoreCase(contactList[i].lname)> 0) {
                temp = contactList[j];
                contactList[j] = contactList[i];
                contactList[i] = temp;
            }
        }
    }listAllContacts();
}
public static void CopyPhoneBookToFile(String FileName) throws Exception{
    FileOutputStream out = new FileOutputStream(FileName);
    PrintStream P = new PrintStream( out );
    for (int i=0; i < num_entries; i++) {
        P.println(
                contactList[i].fname + "\t" +
                        contactList[i].lname + "\t" +
                        contactList[i].number + "\t" +
                        contactList[i].note);
    }
}

public static void removeEntry1(String number) {
    Entry[] newcontactList = new Entry[contactList.length];
    int i = 0;
    for(Entry e : contactList) {
        if(e == null) break; // if an entry is null then break the loop
        if(e.number.equals(number)) // if the given number matches the current number
            continue; // then skip
        newcontactList[i++] = e;
    }
    num_entries--; // decrease the number of entries by 1;
    contactList = newcontactList;
}
public static void sortListByPhoneNumber() {
    int i;
    Entry temp;
    for (int j = 0; j < num_entries; j++) {
        for (i = j + 1; i < num_entries; i++) {
            if (contactList[j].number.compareToIgnoreCase(contactList[i].number) > 0) {
                temp = contactList[j];
                contactList[j] = contactList[i];
                contactList[i] = temp;
            }
        }
    }
    listAllContacts();
}
}

最佳答案

问题是,当您遍历for (Entry e : contactList)中的contactList时,您并未检查整个列表!

例如。如果在第一个循环中e.number不等于新数字,则转到else语句并中断循环,然后转到contactList[num_entries].number = number;并保存可能已经存在的数字;

要以最少的更改来修复代码-只需删除else{ break;}

如果您想要一个更安全,更高效的解决方案,请对contactList使用HashSet数据结构,或者如果希望对其进行排序,请使用TreeSet-这将确保您永远不会有重复的条目,可以使用Set.contains (数字)来检查条目是否已经存在,另外,HashSet会提高对O(1)的条目查找的复杂性,TreeSet会使O(logn)稍差-要么更好,然后遍历整个数组(即O(n))。

10-01 21:41