Java 首先将第一个输入保存在文件夹中,然后引用它

Java 首先将第一个输入保存在文件夹中,然后引用它,java,input,Java,Input,我需要我的程序检测它的联系人列表中以前的条目,并拒绝用户输入两个相同的条目。我一直在尝试,但我要么允许每个条目,要么无效的条目仍然保存到我的列表中 我想要的是让我的程序成为一个电话簿,现实生活中没有两个人应该有相同的号码。这就是为什么我希望任何给定号码都只有一个联系人 以下是我检查条目的代码: System.out.print("Enter Number: "); number = stdin.nextLine(); // read the number while(!numb

我需要我的程序检测它的联系人列表中以前的条目,并拒绝用户输入两个相同的条目。我一直在尝试,但我要么允许每个条目,要么无效的条目仍然保存到我的列表中

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

以下是我检查条目的代码:

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();
}
}
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.PrintStream;
导入java.util.Scanner;
班级报名{
公共字符串fname、lname、number、note;
}
类PBN{
公共静态条目[]联系人列表;
公共静态int num_条目;
公共静态扫描仪stdin=新扫描仪(System.in);
公共静态void main(字符串args[])引发异常{
扫描仪s=新的扫描仪(System.in);
int i;
字符C;
字符串代码,命令;
联系人列表=新条目[999];
num_条目=0;
试一试{
readPhoneBook(“PhoneBook.txt”);
}catch(filenotfound异常){}
System.out.println(“代码输入为1到8个字符。\n”+
“使用命令:\n”+
输入新联系人的\“e\”\n+
“f”用于按姓氏查找联系人,\n+
“\'r\'用于按姓氏查找联系人,\n”+
“y”用于按电话号码查找联系人,\n+
“l”用于列出所有现有联系人,\n+
“d”用于按电话号码删除联系人,\n+
“\'a\”用于按名字字母顺序排序,\n”+
“n”表示按姓氏字母顺序排序,\n+
“p”表示按编号排序,\n+
“\'q\'退出。”);
Command=null;
C='';
while(true){//无限循环
系统输出打印(“命令:”);
Command=stdin.nextLine();
C=命令字符(0);
开关(C){
案例“e”:addContact();break;
案例“f”:
System.out.print(“按姓名搜索联系人:”);
code=stdin.next();
stdin.nextLine();
索引(代码);中断;
案例“r”:
System.out.print(“按姓氏搜索联系人:”);
code=stdin.next();
stdin.nextLine();
index1(代码);中断;
案例“y”:
System.out.print(“通过电话号码搜索联系人:”);
code=stdin.next();
stdin.nextLine();
index2(代码);中断;
案例“l”:
listAllContacts();断开;
案例'q'://当用户想要退出时
CopyPhoneBookToFile(“PhoneBook.txt”);
System.out.println(“退出应用程序。所有条目都是”
+“存储在文件PhoneBook1.txt中”);
System.exit(0);//只需终止执行
案例“a”:
sortList1();
打破
案例“n”:
sortList2();
打破
案例“p”:
sortListByPhoneNumber();
打破
案例“d”://m用于删除联系人;按电话号码删除
System.out.print(“输入要删除的联系人的电话号码:”);
String number=stdin.nextLine();//读取联系人号码
removeEntry1(数字);//从条目中删除数字
打破
违约:
System.out.println(“命令无效,请重新输入命令!!!”;
}
}
}
公共静态void readPhoneBook(字符串文件名)引发异常{
文件F;
F=新文件(文件名);
扫描器S=新扫描器(F);
而(S.hasNextLine()){
联系人列表[num_entries]=新条目();
联系人列表[num_entries].fname=S.next();
联系人列表[num_entries].lname=S.next();
联系人列表[num_entries].number=S.next();
联系人列表[num_entries]。注意=S.nextLine();
num_条目++;
}
S.close();
}
公共静态void addContact(){
System.out.print(“输入名字:”);
字符串fname=stdin.nextLine();
字符串名称;
字符串编号;
字符串模式=“^\\((\\d{3})\\)?[-](\\d{3})[-](\\d{4})$”;
而(fname.length()>8 | | fname.length()<1){
System.out.println(“名字必须在1到8个字符之间”);
System.out.print(“输入名字:”);
fname=stdin.nextLine();
}
联系人列表[num_entries]=新条目();
联系人列表[num_entries].fname=fname;
System.out.print(“输入姓氏:”);
lname=stdin.nextLine();
而(lname.length()>8 | | lname.length()<1){
System.out.println(“名字必须在1到8个字符之间”);
System.out.print(“输入名字:”);
lname=stdin.nextLine();
}
联系人列表[num_entries].lname=lname;
系统输出打印(“输入编号:”);
number=stdin.nextLine();//读取数字
而(!number.matches(pattern)){//只要用户没有输入正确的格式,循环
System.out.println(“错误!”);
System.out.println(“数字格式不正确!使用\“012-3456\”,\“(012)345-6789)”+
,或“012-345-6789”格式);
系统输出打印(“输入编号:”);
number=stdin.nextLine();
用于(条目e:联系人列表){
如果(例如,数字等于(数字)){
System.out.println(“此电话号码已存在。请检查联系人”);
System.out.println(“”);
打破
}否则{
返回;
}
}
}
联系人列表[num\u条目]。编号=编号;
系统输出打印(“输入注释:”);
接触式
boolean isPresent = false;    
for (Entry e : contactList) {
    if (e.number.equals(number)) {
        System.out.println("This phone number already exist. Please check contacts.");
        System.out.println("");
        isPresent = true;
        break;
     }
}
if (!isPresent) {
   contactList[num_entries].number = number;

   //rest of code
}
Optional<String> presentPh = Arrays.stream(contactList).filter(e -> e.number.equals(number)).findAny();
if (!presentPh.isPresent()) {
    contactList[num_entries].number = number;

   //rest of code
}