AddressBook Program删除和搜索方法空指针异常

时间:2015-03-07 22:21:47

标签: java class methods

EDIT5:我的remove()方法要求删除一个名称,无论我输入什么名称,都会删除数组中的最新名称。我不知道如何解决这个问题,我的搜索数组会询问一个名称然后声明一个空指针异常错误。我的其余代码如下所示。

 case 3: //Remove a contact
        System.out.print("Full name to remove: ");
        Scanner rs = new Scanner(System.in);
        String deleteName = rs.nextLine();
        a1.remove(deleteName);
        break;

case 4: //search a contact
        System.out.print("Full name to search: ");
        Scanner ss = new Scanner(System.in);
        String searchName = ss.nextLine();
        a1.search(searchName);
        break;

EDIT4:弄清楚初始化问题..我不相信我错过了这么简单的事情。我的程序现在几乎完美,除了我的删除函数,遇到空指针异常。有人可以向我解释为什么会这样吗?我还更新了代码

EDIT3:我现在没有在我的Contact和AddressBook课程中对我大喊大叫。我只需要知道如何在主要工作中制作我的方法。正如有人在评论中指出的那样,我需要初始化我的方法和类。有人可以告诉我在哪里需要放置我的构造函数,这些方法可以工作吗?我把它们放在我程序的多个区域已经无济于事了。

我正在为我的java类工作一个AddressBook程序。我已经构建了所有内容,但是我在其他类中的方法给了我一些困难(我将所有方法公开,并将我的类特定变量设为私有)。另外,我想就如何构建我的方法提供一些反馈。我粗略地概述了这里使用的方法:

Contact
-firstName:String
-lastName:String
-phone:String
+Contact(firstName:String,lastName:String, phone:String)
+getFullName():String
+getLastName():String
+getPhone():String
+setFirstName(firstName:String):void
+setLastName(lastName:String):void
+setPhone(phone:String):void
+equals(o:Object):boolean #currently not sure how to do this method
+toString():String

AddressBook class
-contacts:Contact[]
- count:int;
-fileName:String
+AddressBook(fileName:String)
+add(Contact c):boolean
+remove(fullName:String):boolean
+search(fullName:String):Contact
+display():void
+load():boolean
+save():boolean
+search(String fullName):boolean

这是我的代码:

联系班级代码:

public class Contact {
private String firstName;
private String lastName;
private String phone;

public Contact(String firstName, String lastName, String phone) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.phone = phone;
}

public String getFullName(){
    return firstName + " " + lastName;
}

public String getFirstName(){
    return firstName;
}

public String getLastName(){
    return lastName;
}

public String getPhone(){
    return phone;
}

public void setFirstName(String firstName){
    this.firstName = firstName;
}

public void setLastName(String lastName){
    this.lastName = lastName;
}

public void setPhone(String phone){
    this.phone = phone;
}

/*public boolean equals(Contact o){ //not sure how to use this method, tips/suggestions?

}*/

public String toString(){
    return firstName + ":" + lastName + ":" + phone;
}   
}

AddressBook Class

import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

public class AddressBook {
private Contact[] contacts = new Contact[100];
private int count = 0;
private String fileName;

public AddressBook(String fileName) {
    this.fileName = fileName;
}

public boolean add(Contact c) {
    // Checks to see if the array is full
    if (count > 99) {
        return false;
    }
    // Adds the new contact into the array
    contacts[count] = c;

    // increment count
    count++;
    return true;
}

public boolean remove(String deleteName) {          //switched fullName to deleteName to avoid duplicate variable problems
    for (int i = 0; i < count; i++) {
        if(contacts[i].getFullName() == deleteName) {
            contacts[i] = null;
            contacts[i] = contacts[i-1];
        }
    }
    count--;
    return true;
}


 public Contact search(String searchName){      //switched fullName to searchName to avoid duplicate variable problems in the main class
     for(int i = 0; i < contacts.length; i++){ 
         if (contacts[i].getFullName() == searchName) {
             return contacts[i]; 
             } 
         } return null; 
        }


public void display() {
    System.out.println("Name               Phone Number");      //setting up the format for displaying contacts
    System.out.println("-------------------------------");
    for (int i = 0; i < count; i++) {                           //for loop printing out and displaying contacts
        System.out.println(contacts[i].getFirstName() + " "
                + contacts[i].getLastName() + "\t\t"
                + contacts[i].getPhone());
    }
    System.out.println("-------------------------------");
}

public boolean load() {
    //reads the file address.txt and loads it
    try {
        File fr = new File(fileName);
        Scanner s = new Scanner(fr);
        while(s.hasNextLine()) {
            String oStore = s.nextLine();                                   //Storing the line of string here so it can be split
            String[] aStore = oStore.split(":");                            //Splits oStore up and inputs the values into constructor
            contacts[count]=new Contact(aStore[0], aStore[1], aStore[2]);   
            count++;//increments count each contact
        }
        s.close();
        return true;
    } catch (Exception e){
        return false;
    }
}

public boolean save() {
    // Writes the new contact into the file address.txt
    try {
        FileWriter fw = new FileWriter(fileName);
        for (int i = 0; i < contacts.length; i++) {
            fw.write(contacts[i].getFirstName() + ":"
                    + contacts[i].getLastName() + ":"
                    + contacts[i].getPhone() + "\n");
        }
        fw.close();
    } catch (Exception e) {
        return false;
    }
    return true;
}

/*public boolean search(String searchName) {    //switched fullName to searchName to avoid duplicate variable problems in the main class
    for(int i = 0; i <contacts.length; i++){ 
         if (contacts[i].getFullName() == searchName) {
             return contacts[i].getFullName() + contacts[i].getPhone(); 
             } 
         }
    return true;
}*/
}

主类

import java.util.Scanner;

public class Main {
public static void main(String[] args) {

    AddressBook a1 = new AddressBook("address.txt");


    boolean pQuit = false; //boolean value to end the program

    a1.load();
    System.out.println("Welcome. Address book is loaded.");
    System.out.println("");

    do{
     //Setting up the initial menu
    System.out.println("What would you like to do?");
    System.out.println("1)  Display all contacts");
    System.out.println("2)  Add a contact");
    System.out.println("3)  Remove a contact");
    System.out.println("4)  Search a contact");
    System.out.println("5)  Exit");
    System.out.println("Your choice: ");

    Scanner s = new Scanner(System.in); //Scanner for user's choice
    int choice = s.nextInt(); //User picks menu choice
    System.out.println("\n");//line break

    switch(choice){
    case 1: //Display all contacts
        a1.display();
        break;
    case 2: //Add a contact
        System.out.print("First name:");
        String firstName = s.next(); //Stores first name in firstName
        System.out.print("Last name:");
        String lastName = s.next(); //Stores last name in lastName
        System.out.print("Phone number:");
        String phone = s.next();
        a1.add(new Contact(firstName,lastName,phone));
        System.out.println("Contact added.");
        break;
    case 3: //Remove a contact
        System.out.print("Full name to remove: ");
        Scanner rs = new Scanner(System.in);
        String deleteName = rs.nextLine();
        a1.remove(deleteName);
        break;
    case 4: //search a contact
        System.out.print("Full name to search: ");
        Scanner ss = new Scanner(System.in);
        String searchName = ss.nextLine();
        a1.search(searchName);
        break;
    case 5: //exit the program
        a1.save();
        System.out.println("Addres book is saved to file.");
        pQuit = true;
        break;
    default:
        System.out.println("That is not a valid input.");
    }
    }while (pQuit == false);
}
}

现在在我的main方法中,没有一个我调用的方法,因为它们是未定义的。当我尝试在我的+ equals(o:Object):boolean方法中使用contacts数组时,发生了同样的情况。非常感谢所有帮助,如果您发现我的方法有任何问题或任何事情我可以修复和改进,请告诉我!

提前感谢您的帮助。

EDIT1:另请注意我给出的两种搜索方法。我几乎为两者构建了相同的代码。 Eclipse现在正在大喊我告诉我改变方法的名称。我想知道我是否错误地构造了这些方法,或者为什么我会在程序中使用两个相同的命名方法。

EDIT2:已更新为我的新代码。改变了一些事情,方法仍然不起作用。

0 个答案:

没有答案